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
fromspecifies a
range
variable and
the data
source to
query
the wherespecifies 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
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.
Test App
conditional
AND (&&)
operator can
be used to
combine
conditions.
An orderbyclause 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
ToStringmethod that
returns a
stringrepresentation
of the object.
15
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