Upload
ngoxuyen
View
246
Download
1
Embed Size (px)
Citation preview
CS313D: ADVANCED
PROGRAMMING LANGUAGE
Lecture 10: introduction to LINQ Computer Science
department
Lecture Contents
dr. Amal Khalifa, Spr 17
2
What is LINQ?
What is a query?
Query on arrays
Query on a Generic List
Query
dr. Amal Khalifa, Spr 17
3
A query: to request information that
satisfies given criteria.
SQL is the international standard used to
perform and to manipulate data in a database.
LINQ (Language-Integrated Query) allow to
write query expressions that retrieve
information from a variety of data sources, not
just databases.
LINQ to Objects can be used to filter arrays and
Lists, selecting elements that satisfy a set of
conditions
Using LINQ on Arrays
dr. Amal Khalifa, Spr 17
4
Repetition statements that filter arrays focus on the
steps required to get the results imperative
programming.
LINQ queries, specify what to do not how to do it
declarative programming
Example
from
specifies a
range
variable and
the data
source to
query
the where
specifies the
condition
select
determines
the results
dr. Amal Khalifa, Spr 17
5
Example
The orderby
clause sorts
the query
results in
ascending
order.
The
descending
modifier sorts
the results in
descending
order.
dr. Amal Khalifa, Spr 17
6
Example
A LINQ query
returns an
IEnumerable<T>
object
dr. Amal Khalifa, Spr 17
7
dr. Amal Khalifa, Spr 17 8
Using LINQ on an Array of Objects
dr. Amal Khalifa, Spr 17
9
LINQ is not limited to querying arrays of simple
types such as integers.
The following example uses LINQ to query an
array of Employee objects.
The Employee Class
dr. Amal Khalifa, Spr 17
10
dr. Amal Khalifa, Spr 17 11
Test App
dr. Amal Khalifa, Spr 17
12
Test App
conditional
AND (&&)
operator can
be used to
combine
conditions.
An orderby
clause can
sort the results
according to
multiple
properties
dr. Amal Khalifa, Spr 17
13
Test App
Any checks if there is at least one element.
First returns the first element in the result.
Distinct removes duplicate elements
Projection performs a transformation on the data
dr. Amal Khalifa, Spr 17
14
Test App
dr. Amal Khalifa, Spr 17
When the
compiler
creates an
anonymous
type, it
automatically
generates a
ToString
method that
returns a
string
representation
of the object.
15
dr. Amal Khalifa, Spr 17 16
Querying a Generic Collection
dr. Amal Khalifa, Spr 17
17
You can use LINQ to Objects to query List just as arrays.
Although commonly used, arrays have limited capabilities.
A List is similar to an array but provides additional functionality, such as dynamic resizing.
Example
let used to
create a new
range
variable to
store a
temporary
result for use
later in the
LINQ query.
dr. Amal Khalifa, Spr 17
18
dr. Amal Khalifa, Spr 17 19
Chapter 9: 9.1, 9.2, 9.3, 9.5
That’s all
dr. Amal Khalifa, Spr 17
20
Case Study 21
dr. Amal Khalifa, Spr 17
Q:
dr. Amal Khalifa, Spr 17
22