Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Sudhir Chandravanshi
20 July 2009
1
Introducing Linq
LINQ Introduction
2
Introducing Linq
Overview
3
Introducing Linq
Overview (2)
4
Introducing Linq
What Is LINQ?
5
Introducing Linq
What Is LINQ?
6
Introducing Linq
•A query expression:
7
Introducing Linq
8
Introducing Linq
•A LINQ query is not really executed until there is access to the query
result
9
Introducing Linq
10
Introducing Linq
class Customer{
public string Name;
public string City;
public Order[] Orders;}
11
Introducing Linq
12
Introducing Linq
var query =
from p in products
where p.IdProduct == 3
from o in p.Orders
select o;
13
Introducing Linq
•If you have entity relationships in your data model, you can still use
explicit relationships in a LINQ:
var query =
from c in Customers
join s in Suppliers on c.City equals s.City
select new { c.City, c.Name, SupplierName =
s.Name };
14
Introducing Linq
•LINQ can return a hierarchy or graph of objects for a SQL query that
contains several entities with one or more one-to-many relationships:
var query =
from c in Customers
join s in Suppliers
on c.City equals s.City into customerSuppliers
select new { c.City, c.Name, customerSuppliers };
15
Introducing Linq
•LINQ requires to describe your data in terms of entities that are also
types in the language
•A LINQ query, it is always a set of operations on instances of some
classes
• These objects might be the real container of data, or they might be a
simple description (in terms of metadata) of the external entity one is
going to manipulate
16
Introducing Linq
[Table("Products")]
public class Product {
[Column(IsPrimaryKey=true)] public int IdProduct;
[Column(Name="UnitPrice")] public decimal Price;
[Column()] public string ProductName;
[Column()] public bool Taxable;
[Column()] public decimal Tax; }
17
Introducing Linq
var taxableProducts =
from p in db.Products
where p.Taxable == true
select p;
db.SubmitChanges();
18
Introducing Linq
XML Manipulation
19
Introducing Linq
20
Introducing Linq
21
Introducing Linq
22
Introducing Linq
Language Integration
23
Introducing Linq
Language Integration
24
Introducing Linq
Type Checking
25
Introducing Linq
•The type system of the Microsoft .NET Framework and the type
system of SQL Server are different
•Using LINQ, we give precedence to the .NET type system because it
is the one supported by any language that hosts a LINQ query
•It is necessary to convert many types of data between these two
worlds
•LINQ handles this conversion for you automatically, making the
differences in type systems almost completely transparent to the
programmer
26
Introducing Linq
LINQ Flavors
27
Introducing Linq
LINQ to Objects
28
Introducing Linq
LINQ to ADO.NET
29
Introducing Linq
LINQ to XML
var book =
new XElement( "Book",
new XAttribute( "Title", "Introducing LINQ" ),
from person in team
where person.Role == "Author“
select new XElement( "Author", person.Name
) );
30
Introducing Linq
C# Language Features
31
Introducing Linq
int a = 5, b = 10;
int c = (int) Min( a, b );
32
Introducing Linq
33
Introducing Linq
34
Introducing Linq
void CreateInstance() {
SimpleDelegate a = new SimpleDelegate( MethodA );
ReturnValueDelegate b = new ReturnValueDelegate (
MethodB );
TwoParamsDelegate c = new TwoParamsDelegate(
MethodC );
// … } }
35
Introducing Linq
void CreateInstance() {
SimpleDelegate a = MethodA;
ReturnValueDelegate b = MethodB;
TwoParamsDelegate c = MethodC;
// … }
// … }
36
Introducing Linq
void Run2() {
int counter = 0;
this.Repeat10Times( delegate { Console.WriteLine(
"C# chapter" );
counter++; } );
Console.WriteLine( counter ); } // … }
37
Introducing Linq
void Run3() {
Repeat10Times(
delegate( string text, int age )
{ Console.WriteLine( "{0} {1}", text, age ); } );
}
// … }
38
Introducing Linq
39
Introducing Linq
•C# 2.0 introduced the yield statement through which the compiler
automatically generates a class that implements the IEnumerator
interface returned by the GetEnumerator method
•The yield statement can be used only immediately before a return or
break keyword
•Enumeration using a yield statement :
40
Introducing Linq
41
Introducing Linq
IEnumerator IEnumerable.GetEnumerator() {
return this.GetEnumerator(); }
42
Introducing Linq
43
Introducing Linq
•When var is used, the compiler infers the type from the expression used to
initialize the variable. The compiled IL code contains only the inferred type.
44
Introducing Linq
45
Introducing Linq
•The sample shows some cases in which the var keyword is not allowed:
class VarDemo {
// invalid token 'var' in class, struct or interface
member declaration
var k =0;
// type expected in parameter list
public void InvalidUseParameter( var x ){}
// type expected in result type declaration
public var InvalidUseResult() { return 2; }
46
Introducing Linq
47
Introducing Linq
48
Introducing Linq
•A projection is an expression that returns a type different from the type of its
single parameter:
// Projection: takes a string and returns an int
( s ) => s.Length
49
Introducing Linq
50
Introducing Linq
51
Introducing Linq
•C# 3.0 introduces a syntax that conceptually extends an existing type (either
reference or value) by adding new methods without deriving it into a new type
•The methods that extend a type can use only the public members of the type
itself, just as you can do from any piece of code outside the target type
•An extension method must be static and public, must be declared inside a
static class, and must have the keyword this before the first parameter type,
which is the type that the method extends
•Extension methods are public because they can be (and normally are) called
from outside the class where they are declared
•However, the result type of the extension method might be the extended type
itself
•LINQ very frequently uses extension methods in this way
52
Introducing Linq
53
Introducing Linq
54
Introducing Linq
55
Introducing Linq
y =
y.Increase().Double().Decrease().Decrease().Triple().Half(
);
56
Introducing Linq
57
Introducing Linq
public class B : A {
public override void X() {}
public void Y() {} }
58
Introducing Linq
59
Introducing Linq
•C# 3.0 introduces a shorter form of object initialization syntax that generates
functionally equivalent code:
60
Introducing Linq
61
Introducing Linq
62
Introducing Linq
63
Introducing Linq
64
Introducing Linq
•An object initializer can also be used without specifying the class that will be
created with the new operator
•Doing that, a new class—an anonymous type—is created
•Consider the example shown below :
Customer c1 = new Customer { Name = "Marco" };
var c2 = new Customer { Name = "Paolo" };
var c3 = new { Name = "Tom", Age = 31 };
var c4 = new { c2.Name, c2.Age };
var c5 = new { c1.Name, c1.Country };
var c6 = new { c1.Country, c1.Name };
65
Introducing Linq
•C# 3.0 also introduces query expressions, which have a syntax similar to the
SQL language and are used to manipulate data
•This syntax is converted into regular C# 3.0 syntax that makes use of specific
classes, methods, and interfaces that are part of the LINQ libraries
66
Introducing Linq
67
Introducing Linq
•The following code shows a prototype of the full syntax of a LINQ query
expression:
query-expression ::=
from-clause
query-body query-body
::= join-clause* (from-clause join-clause* | let-clause | where-
clause)*
orderby-clause? (select-clause | groupby-clause)
query-continuation?
from-clause ::= from itemName in srcExpr
select-clause ::= select selExpr
groupby-clause ::= group selExpr by keyExpr
The first from clause can be followed by zero or more from, let, or where
clauses.
68
Introducing Linq
A from clause can be followed by any number of join clauses. The final select
or group clause can be preceded by an orderby clause that applies an ordering
to the results:
join-clause ::= join itemName in srcExpr on keyExpr equals
keyExpr (into itemName)?
69