WINDOWS PROGRAMMING
(With C#.NET)
Chapter 5:
LINQ
TS. Lê Văn Vinh
Khoa Công nghệ Thông tin
Trường ĐHSPKT TP. HCM
Contents
Introduction
LinQ to Objects
LinQ to SQL
2
Introduction
Traditionally, queries against data are expressed as
simple strings without type checking at compile time
or IntelliSense support
Different query language for each type of data source:
SQL databases, XML documents, various Web
services, and so on
=> Language-Integrated Query (LINQ) is an innovation
that bridges the gap between the world of objects and
the world of data.
3
Introduction
4
Introduction
Architecture
C# VB.NET Others
.NET Language Integrated Query (LINQ)
LINQ data source providers
ADO.NET support for LINQ
LINQ LINQ LINQ LINQ LINQ
to Objects to Datasets to SQL to Entities to XML
Introduction
An example (The tradional way)
Find the names of all London customers:
List<string> londoners = new List<string>();
foreach (Customer c in customers) {
if (c.City == “London”) {
londoners.add(c.Name);
}
}
6
Introduction
An example (The LINQ way)
Returns a simple array!
string[] londoners =
from c in customers
where c.City == “London”
select c.Name;
Declarative!
No loops!
SQL-like!
7
Contents
Introduction
LINQ to Objects
LINQ to SQL
8
Three Parts of a Query Operation
All LINQ query operations consist of three
distinct actions: class IntroToLINQ
{
• Obtain the data source. static void Main()
{
• Create the query. // The Three Parts of a LINQ Query:
// 1. Data source.
• Execute the query. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
9
LINQ and Generic Types
IEnumerable is the interface that enables generic
collection classes to be enumerated by using
the foreach statement
The var keyword
IEnumerable<Customer> customerQuery =
from cust in customers
where cust.City == "London"
select cust;
foreach (Customer customer in customerQuery)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
var customerQuery2 =
from cust in customers
where cust.City == "London"
select cust;
foreach(var customer in customerQuery2)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
10
LINQ Query operation
Restriction Where
Projection Select, SelectMany
Ordering OrderBy, ThenBy
Grouping GroupBy
Quantifiers Any, All
Partitioning Take, Skip, TakeWhile, SkipWhile
Sets Distinct, Union, Intersect, Except
Elements First, FirstOrDefault, ElementAt
Aggregation Count, Sum, Min, Max, Average
Conversion ToArray, ToList, ToDictionary
Casting OfType<T>
11
LINQ Query operation
List of basic operations
Obtaining a Data Source: from
Filtering: where
Ordering: orderby
Grouping: group
Joining: Join
Selecting: Select
Please study how to use the above operations.
Source: https://msdn.microsoft.com/en-
us/library/bb397927.aspx
12
Data Transformations with LINQ
Select a subset of each element in the
source sequence
var query = from cust in Customers
select cust.City;
var query = from cust in Customer
select new {Name = cust.Name, City = cust.City};
13
Data Transformations with LINQ
Three types of ways to transform the
source data
Do not transform the source data
14
Data Transformations with LINQ
Three types of ways to transform the
source data
Transform the source data
15
Data Transformations with LINQ
Three types of ways to transform the
source data
Transform the source data
16
Data Transformations with LINQ
Three types of ways to transform the
source data
Let the compiler infer type information
17
Lambda Expressions
A lambda expression is an anonymous function that
you can use to create delegates or expression
tree types.
By using lambda expressions, you can write local
functions that can be passed as arguments or
returned as the value of function calls.
Lambda expressions are particularly helpful for writing
LINQ query expressions.
(input parameters) => expression / statement
Return the value of the RIGHT side.
18
Lambda Expressions
int i = this.compute(10);
private int compute(int value)
{
return (value + 2);
}
----------------------------------------------------------
delegate int DelType(int i);
DelType dd = delegate(int value)
{
return (value +2);
};
int i = dd(10);
---------------------------------------------------------------
delegate int DelType(int i);
DelType d = value => value + 2;
int i = d(10);
19
Lambda Expressions
Examples
class SimpleLambda
{
static void Main()
{
// Data source.
int[] scores = { 90, 71, 82, 93, 75, 82 };
// The call to Count forces iteration of the source
int highScoreCount = scores.Where(n => n > 80).Count();
Console.WriteLine("{0} scores are greater than 80", highScoreCount);
// Outputs: 4 scores are greater than 80
}
}
20
Lambda Expressions
Examples
IEnumerable<Product> x =
from p in products
where p.UnitPrice >= 10
select p;
Using Lambda Expression:
IEnumerable<Product> x = products.Where(p => p.UnitPrice >= 10);
21
Lambda Expressions
Examples
IEnumerable<string> productNames = products.Select(p => p.Name);
IEnumerable<string> productNames = from p in products select p.Name;
22
Excercises
Download and work with the 101 samples
from MSDN:
https://code.msdn.microsoft.com/101-
linq-samples-3fb9811b
23
Contents
Introduction
LINQ to Objects
LINQ to SQL
24
LINQ to SQL
Introduction
The data model of a relational database is mapped to
an object model expressed in the programming
language of the developer
To access SQL databases just as you would access
an in-memory collection.
25
LINQ to SQL
Introduction
26
LINQ to SQL
Introduction
27
LINQ to SQL
Introduction
using System.Data.Linq;
using System.Data.Linq.Mapping;
28
LINQ to SQL
What You Can Do With LINQ to SQL
Connect to a database
Selecting
Inserting
Updating
Deleting
Table<TEntity> Class
https://msdn.microsoft.com/en-
us/library/bb358844(v=vs.110).aspx?cs-save-
lang=1&cs-lang=csharp#code-snippet-1
29
LINQ to SQL
What You Can Do With LINQ to SQL
Connect to a database
• Creating LINQ to SQL Classes (we can use O/R Designer)
• Using the DataContext class:
The DataContext class contains methods and properties for
connecting to a database and manipulating the data in the
database (for example, performing Inserts, Updates, and
Deletes)
• Method: SubmitChanges(): Computes the set of modified
objects to be inserted, updated, or deleted, and executes the
appropriate commands to implement the changes to the
database.
• https://msdn.microsoft.com/en-
us/library/system.data.linq.datacontext.aspx
30
LINQ to SQL
What You Can Do With LINQ to SQL
Selecting
SinhViendbDataContext svDTcontext = new SinhViendbDataContext();
var svQuery = from sinhviens in svDTcontext.SinhViens
where sinhviens.HoTen == “Hung”
select sinhviens;
31
LINQ to SQL
What You Can Do With LINQ to SQL
Inserting:
• Insert to a table:
– InsertOnSubmit() method
– InsertAllOnSubmit() method
SinhViendbDataContext svDTcontext = new SinhViendbDataContext();
SinhVien sv = new SinhVien();
sv.MaSo = txtMaSo.Text;
sv.HoTen = txtHoTen.Text;
Table<SinhVien> t = svDTcontext.SinhViens;//Biến tham chiếu
t.InsertOnSubmit(sv);
t.Context.SubmitChanges();
32
LINQ to SQL
What You Can Do With LINQ to SQL
Updating:
• SingleOrDefault(): Returns the only element of a sequence, or a
default value if the sequence is empty; this method throws an
exception if there is more than one element in the sequence.
SinhViendbDataContext svDTcontext = new SinhViendbDataContext();
var svQuery = (from sinhviens in svDTcontext.SinhViens
where sinhviens.MaSo == txtMaSo.Text
select sinhviens).SingleOrDefault();
if (svQuery != null)
{
svQuery.HoTen = txtHoTen.Text;
svDTcontext.SubmitChanges();
}
33
LINQ to SQL
What You Can Do With LINQ to SQL
Deleting:
• Deleting to a table:
– DeleteOnSubmit() method
– DeleteAllOnSubmit() method
SinhViendbDataContext svDTcontext = new SinhViendbDataContext();
var svQuery = from sinhviens in svDTcontext.SinhViens
where sinhviens.HoTen == txtHoTen.Text
select sinhviens;
svDTcontext.SinhViens.DeleteAllOnSubmit(svQuery);
svDTcontext.SubmitChanges();
34