This document discusses LINQ (Language Integrated Query) and its core concepts and functions. It introduces the LINQ pattern of initializing a query, optionally filtering and sorting, and projecting the results. It then covers the basic LINQ functions of aggregation, projection, and filtering through diagrams and examples. The document provides answers to a question on using LINQ to transform a string by splitting on uppercase letters.
2. Agenda
FEATURING:
# LINQ-WORKHORSES (PART I)
# THE LINQ-PATTERN (PART II)
FROM HUMAN IN CLASS
WHERE HUMAN.ISINTERESTED()
SELECT HUMAN.EARS + HUMAN.EYES
// MAG IK UW AANDACHT?
3. Introduction
LINQ consists of:
syntax The buildingblocks: genrics, anonymous
types, collection- / object-
initializers, lambdas, Ienumerable’s, type inference
semantics The ideas: basic functions, lazyness / deferred
execution, linq-pattern, parsing
Make sure you master them both!
9. The LINQ-pattern
Initializer >> [Filter] >> [Sorter] >> Projector
Initializer from item in collection
[Filter where filter(item)]
[Sorter orderby item.propery]
Projector select item + something
10. The LINQ-pattern Question
Q I am trying to transform a string made of words
starting with an uppercase letter. I want to separate
each word with a space and keep only the first
uppercase letter. All other letters should be lowercase.
For example, "TheQuickBrownFox" would become "The
quick brown fox". Obviously, I could use a simple
foreach and build a string by checking each
character, but I am trying to do it using LINQ. Would
you know how to solve this elegantly using LINQ?
Thank you for your help. (stackoverflow.com)
Dus, "TheQuickBrownFox" -> "The Quick Brown Fox"
11. The LINQ-pattern Answer #1
public string SplitAsWords(string original)
{
var matches = Regex.Matches(original, "[A-Z][a-z]*")
.Cast<Match>();
var str = string.Join(" ", matches
.Select(match => match.Value));
str = str[0] + str.Substring(1).ToLower();
return str;
}
// Hier en daar wat Linq. Lastig te volgen.
12. The LINQ-pattern Answer #2
string phrase = "TheQuickBrownFox";
var invalidChars = from ch in phrase
where char.IsUpper(ch)
select ch;
foreach (char ch in invalidChars)
{
int index = phrase.IndexOf(ch);
phrase = phrase.Remove(index, 1);
phrase = phrase.Insert(index, " " + ch);
}
// Projectie niet in select, maar in aparte iteratie.
13. The LINQ-pattern Answer #3
string str =
(from i in Regex.Split("TheQuickBrownFox", "")
select Regex.IsMatch(i, "[A-Z]") ? " " + i : i)
.Aggregate((str1, str2) => str1 + str2);
// Volgens pattern. Filtering en projectie samen!