Chapter 15. Introduction
to LINQ
Hoang Anh Viet
Hanoi University of Technology
1
Microsoft
Objectives
“LINQ allows you to build strongly typed query expressions,
which can be applied to a number of LINQ targets to
manipulate “data” in the broadest sense of the word.
Here, you will learn about LINQ to Objects, which allows
you to apply LINQ expressions to containers of data
(arrays, collections, custom types). This information will
serve you well when we examine how to apply LINQ
expressions to relational databases (via LINQ to ADO)
and XML documents.”
2
Microsoft
Roadmap
15.1 Understanding the Role of LINQ
15.2 A First Look at LINQ Query Expressions
15.3 LINQ and Generic Collections
15.4 LINQ and Nongeneric Collections
15.5 The Internal Representation of LINQ Query Operators
15.6 Investigating the C# LINQ Query Operators
3
Microsoft
15.1 The Role of LINQ
The LINQ API is an attempt to provide a consistent,
symmetrical manner in which programmers can obtain
and manipulate “data” in the broad sense of the term
LINQ Expressions Are Strongly Typed and Extendable
The Core LINQ Assemblies
System.Core.dll
System.Data.Linq.dll
System.Data.DataSetExtensions.dll
System.Xml.Linq.dll
4
Microsoft
The Role of LINQ
Advantages of LINQ
For now:
Dynamically-created string queries
Doesn't provide compile-time checking
Native code and non-native code is mixed
With LINQ
Static typing
Compile-time syntax checking
IntelliSense
Native code
5
Microsoft
Roadmap
15.1 Understanding the Role of LINQ
15.2 A First Look at LINQ Query Expressions
15.3 LINQ and Generic Collections
15.4 LINQ and Nongeneric Collections
15.5 The Internal Representation of LINQ Query Operators
15.6 Investigating the C# LINQ Query Operators
6
Microsoft
15.2 A First Look at LINQ Query
Expressions
LINQ and Implicitly Typed Local Variables
Type of the variable induced from expression
Must include initializer
Can’t be null. Why not?
What happens if “var” is a class in scope?
Works in for loops
7
Microsoft
LINQ Query Expressions
LINQ and Extension Methods
The Problem: How to add a method to a type you don’t control
and can’t subtype?
Example: How to add Standard Query Operators to
IEnumerable<T>, without deriving a new interface?
Solution: Extension methods aren’t really members of the target
type, but the syntax makes them look that way
Compile-time type safety is preserved
8
Microsoft
LINQ Query Expressions
LINQ and Extension Methods
Not for properties, events, operators
Currently under consideration
Equivalent to calling the static method
Difference from actually extending the class?
How could we use this for Polynomials?
Disadvantages?
Implicitness
Security
9
Microsoft
LINQ Query Expressions
Creating Extension Methods
Define a Static Class
Define a static method whose first argument is an object of type
T
[System.Runtime.CompilerServices.Extension] attribute on first
parameter tells CLR the method is an Extension
C# binds the attribute to keyword “this”
Create a T object, and call the method as if it were a member of
the object
When the compiler fails to find the method among T’s members,
it searches for an extension method in scope with matching
name and signature
10
Microsoft
Replacing LINQ Extension Methods
Extension Methods have lower priority of resolution than type
members
So if a type has a member with same signature as a LINQ
extension method, the type’s member will be called, and there is
no ambiguity
This is how DLINQ and XLINQ replace the default LINQ
implementations of the Standard Query Operators
11
Microsoft
Lambda Expressions
Lambda Expressions
Generalized function syntax
λ x . x + 1
in C# 3.0, have x => x + 1
From anonymous delegate syntax:
delegate(int x) { return x + 1;}
Can have implicitly typed variables
Can have more than one variable
Can have expression or statement body
NB: no statement bodies in preview compiler
12
Microsoft
13
Lambda expressions
Can be converted to delegate type
if parameters and body match
Participate in type inference
If expression body, get expression trees
Lambda Expression
Microsoft
Lambda Expression
Lambda expressions
Type inference
If call Select(customers, c => c.Name);
T, S mapped to appropriate types
14
Microsoft
The Role of Differed Execution
LINQ query expressions are not actually evaluated
until you iterate over their contents
Apply the same LINQ query multiple times to the
same container and obtain the latest and greatest
results
15
Microsoft
The Role of Immediate Execution
To evaluate a LINQ expression from outside the confines
of foreach logic, you are able to call any number of
extension methods defined by the Enumerable type
Extension methods:ToArray<T>,
ToDictionary<TSource,TKey>(), and ToList<T>()
Capture a LINQ query result set in a strongly typed
container
16
Microsoft
Roadmap
15.1 Understanding the Role of LINQ
15.2 A First Look at LINQ Query Expressions
15.3 LINQ and Generic Collections
15.4 LINQ and Nongeneric Collections
15.5 The Internal Representation of LINQ Query Operators
15.6 Investigating the C# LINQ Query Operators
17
Microsoft
15.3 LINQ and Generic Collections
LINQ query expressions can also manipulate data within
members of the System.Collections.Generic namespace,
such as the List<T> type
18
Microsoft
Classes
System.Collections.Generic classes
List<ItemType>
Dictionary<K,V>
Stack<ItemType>
Queue<ItemType>
System.Collections.Generic interfaces
IList<ItemType>
IDictionary<K,V>
ICollection<ItemType>
IEnumerable<ItemType>
IEnumerator<ItemType>
IComparable<OperandType>
IComparer<OperandType>
19
Microsoft
Applying a LINQ Expression
grabbing items from the List<T> where the Speed
property is greater than 55
20
Microsoft
Roadmap
15.1 Understanding the Role of LINQ
15.2 A First Look at LINQ Query Expressions
15.3 LINQ and Generic Collections
15.4 LINQ and Nongeneric Collections
15.5 The Internal Representation of LINQ Query Operators
15.6 Investigating the C# LINQ Query Operators
21
Microsoft
15.4 LINQ and Nongeneric Collections
It is possible to iterate over data contained within
nongeneric collections using the generic
Enumerable.OfType<T>() method
22
Microsoft
Nongeneric Collections
Use the previously defined Car type and import the
System.Collections namespace
23
Microsoft
Roadmap
15.1 Understanding the Role of LINQ
15.2 A First Look at LINQ Query Expressions
15.3 LINQ and Generic Collections
15.4 LINQ and Nongeneric Collections
15.5 The Internal Representation of LINQ Query Operators
15.6 Investigating the C# LINQ Query Operators
24
Microsoft
15.5 The Internal Representation of LINQ
Query Operators
Introduced to the process of building query expressions
using various C# query operators (such as from, in,
where, orderby, and select)
C# compiler actually translates these tokens into calls on
various methods of the System.Linq.Enumerable type
Many methods require a generic delegate of type
Func<>
25