Professional Documents
Culture Documents
Introduction to LINQ 1
C# 3.0
Chapter 23 Introduction to LINQ
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 2
Why LINQ?
Data !!= Objects
State-of-the-art tooling has perfected OO
methodologies
The next challenge:
Accessing
ccess g and
a d integrating
teg at g non-OO
o OO
information, while abstracting away
its source
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 3
LINQ
LINQ is po
powered
ered b
by lang
language
age
enhancements
Some of which we have already seen (C# 3.0)
Some others we will examine in this chapter
C# 30
Introduction to LINQ 4
Implicit Typing
Local variables
ariables can have
ha e an implicit ttype
pe if
initialized within the declaration statement
var
var
var
var
i =5;
s=Hello;
e=newEmployee();
dict =newDictionary<string,List<string>>();
var a;
//Illegal!
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 5
C# 30
Introduction to LINQ 6
Anonymous Types
Remo
Removes
es the b
burden
rden of declaring data
dataholder types
yp
Narrows the Data Objects gap
var pi=new{
i
{
Name=John,
Pay CalcSalary()
Pay=CalcSalary()
};
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 7
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 8
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 9
Expression Trees
An e
expression
pression lambda can be capt
captured
red as
p
tree
an expression
Code = Data
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 10
BinaryExpression
ExpressionType=Multiply
Type=Int32
ParameterExpression
Name=x,Type=Int32
ParameterExpression
Name=y,Type=Int32
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 11
E
Expression
i T
Tree Visualizer
Vi
li
(MSDN
sample)
http://tinyurl.com/ExpTreeVis
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 12
Review So Far
Implicit typing
t ping
Anonymous types
Expression
E
i ttrees
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 13
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 14
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 15
C# 30
Introduction to LINQ 16
Implementing Where
staticclassEnumerableExtensions {
publicstaticIEnumerable<T>Where<T>(
thisIEnumerable<T>source,
Predicate<T>filter)
{
foreach (Telem insource)
if(filter(elem))
yieldreturnelem;
var
ar here is
}
}
IEnumerable<int>
var numbers=Range(0,100);
var evens=numbers.Where(i =>i%2==0);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 17
Order
To order a seq
sequence,
ence we
e must
m st iterate it
relyy on a sorting
first (And
(
g container))
publicstaticIEnumerable<T>Order<T>(
thisIEnumerable<T>source){
SortedDictionary<T,bool>elements=
newSortedDictionary<T,bool>();
foreach (Telem insource)
elements.Add(elem,default(bool));
foreach (Tkeyinelements.Keys)
yieldreturnkey;
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 18
Select
ires a con
erter
Projection req
requires
converter:
//DefinedinSystem.Core.dll
//DefinedinSystem Core dll
publicdelegateTResult Func<T,TResult>(Targ);
publicstaticIEnumerable<S>Select<T,S>(
thisIEnumerable<T>source,
Func<T S>projection){
Func<T,S>projection){
foreach (Telem insource)
yieldreturnprojection(elem);
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 19
Count
Count, First
publicstaticlongCount<T>(
p
g
(
thisIEnumerable<T>source){
longcount=0;
var
ar enumerator=source.GetEnumerator();
en merator so r e GetEn merator()
while(enumerator.MoveNext())
++count;
;
returncount;
}
publicstaticTFirst<T>(
bli t ti TFi t<T>(
thisIEnumerable<T>source){
var enumerator=source.GetEnumerator();
();
if(enumerator.MoveNext())
returnenumerator.Current;
//Th
E t
//Throw:Emptysource
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 20
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 21
Deferred Execution
ch as
Statements ssuch
var numbers=Range(0,100);
var evens=numbers.Where(i =>i%2==0);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 22
Deferred Execution
This infers interesting conseq
consequences:
ences
We can produce infinite streams:
IEnumerable<int>Primes(int start){
for(;;++start)
if(IsPrime(start))
yieldreturnstart;
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 23
Review So Far
Q
Query
er operators as declarative
declarati e
p g
programming
g
Our hand-rolled query operators
Deferred
e e ed execution
e ecu o
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 24
C# 30
Introduction to LINQ 25
N
Note: S
So ffar we h
have di
discussed
d LINQ to
Objects query operators
Other LINQ provides do not work with IEnumerable
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 26
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 27
{
ProductName =grp.Key,
Count grp.Count()
Count=grp.Count()
});
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 28
C# integrated
g
q
query
y operators:
p
Projection: select
Filtering: where
Grouping: groupby
Od i
Ordering:
orderby
d b
Miscellaneous: join, let
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 29
var here is
IEnumerable<Anon>
bl
var here is
IGrouping<string,Anon>
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 30
Syntactic Sugar
Lang
Language
age query
q er operators translate
y to LINQ q
query
y operators
p
directly
Query operators can be mixed:
int cnt =
(fromi inEnumerable.Range(0,100)
wherei %2==0
selecti).Count(i =>i >25);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 31
C# 30
Introduction to LINQ 32
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 33
LINQ to Objects
LINQ to Objects relies on the Enumerable
En merable
class, which contains q
query
y operators
p
as
extension methods
Any IEnumerable<T> can be queried
Additional types can be queried if they
implement the query pattern
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 34
Query Pattern
If the type is not IEnumerable,
IEn merable there are
y to make it q
queryable:
y
two ways
Add instance methods for query operators:
Select<T>, Where, OrderBy, etc.
Add extension methods in a separate
p
class for q
query
y
operators: Select<T>, Where, OrderBy, etc.
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 35
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 36
C# 30
Introduction to LINQ 37
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 38
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 39
Make
M k your object
bj t models
d l LINQ
LINQ-friendly!
f i dl !
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 40
LINQ to Strings
strings=Guid.NewGuid().ToString();
stringdigitsOnly =
newstring((fromcins
whereChar.IsDigit(c)
selectc)
)
.ToArray());
Console.WriteLine(s+\n+digitsOnly);
//Output:
8faf837df0a64e698ac523635452f6f9
883706469852363545269
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 41
LINQ to Reflection
//Findallcollection initializable types
//Findallcollectioninitializable
//(Roughsketch)
var queryableTypes =
fromasm inAppDomain.CurrentDomain.GetAssemblies()
fromtinasm.GetExportedTypes()
wheret GetInterfaces() Any(itf =>
wheret.GetInterfaces().Any(itf
itf.IsGenericType &&
((itf.IsGenericTypeDefinition
&&itf ==typeof(ICollection<>))||
||
(!itf.IsGenericTypeDefinition &&
itf GetGenericTypeDefinition()==
itf.GetGenericTypeDefinition()==
typeof(ICollection<>)))
)||
typeof(IEnumerable).IsAssignableFrom(t)&&
t.GetMethods().Any(m=>m.Name =="Add")
selectt;
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 42
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 43
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Introduction to LINQ 44
Chapter 23 Exercises
C# 30
Introduction to LINQ 45
Chapter Summary
More C# 3.0
3 0 language features
Anonymous types, implicit typing, expression trees
C# 3.0
3 0 meets LINQ
Query operators, query pattern
LINQ to Objects
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel