LINQ: A Introduction
Speaker: Arvind Kumar
Agenda
What is LINQ
Queries without LINQ
Key features of LINQ
LINQ Architecture
What is LINQ?
Language Integrated Query
Make query a part of the language
Component of .NET Framework 3.5
Why
Most programmers today are required to
integrate some sort of data into their
applications.
Often, you have to take data from multiple
sources such as memory collections,
relational databases, XML files, etc.
With the current implementation of .NET
Framework, getting to this data is often
tedious and requires familiarity with
multiple data access technologies and XML
APIs.
Why
All data sources have different means of
querying the data in them: SQL for
databases, XQuery for XML, LDAP queries
for Active Directory etc.
Today's data access story lacks a unified
approach to accessing data from disparate
data sources, which is exactly what the
LINQ (Language Integrated Query) family of
technologies are intended to solve.
Introduction to LINQ
Query (LINQ), is a component released
within the .NET 3.5 Framework. It is one of
the most powerful features of .NET 3.5. It
serves the purpose of querying objects.
LINQ comprises a series of operators, which
are used to query, filter and project data in
arrays, enumerable classes, relational
databases and XML.
Introduction to LINQ
In order to query data, the data needs to be
encapsulated as an object. In case the data
source is not an object, it first needs to be
converted to an object in order for LINQ to
query it.
The LINQ concept treats the data source as
an Object, rather than a Database. So we
may say, its an object that is queried.
LINQ Architecture
Advantages of LINQ
Because LINQ is integrated into the C#
language, it provides syntax highlighting
and IntelliSense. These features make it
easy to write accurate queries and to
discover mistakes at design time.
Because LINQ queries are integrated into
the C# language, it is possible for you to
write code much faster than if you were
writing old style queries. In some cases,
developers have seen their development
time cut in half
Advantages of LINQ
The integration of queries into the C#
language also makes it easy for you to step
through your queries with the integrated
debugger.
The hierarchical feature of LINQ allows you
to easily see the relationship between
tables, thereby making it easy to quickly
compose queries that join multiple tables
10
Advantages of LINQ
The unified programming of LINQ allows you
to use a single LINQ syntax when querying
multiple data sources.
This allows you to get up to speed on new
technologies much more quickly.
If you know how to use LINQ to Objects, it is
not hard to learn how to use LINQ to SQL,
and it is relatively easy to master LINQ to
XML.
11
Advantages of LINQ
Because LINQ is declarative, it usually
allows you to write concise code that is easy
to understand and maintain.
The compiler and provider translate
declarative code into the code that is
actually executed. As a rule, LINQ knows
more than the average developer about
how to write highly optimized, efficient
code.
12
LINQ Syntax
LINQ query syntax is a set of query
keywords built into the .NET framework (3.5
and higher) that allow the developer to
write SQL style commands in line straight in
the code editor, without the use of quotes.
13
LINQ Syntax
The .NET framework introduces us to the
following query keywords;
from / in -Specifies the data source
where -Conditional boolean expression (e.g. i
== 0)
orderby (ascending/descending) -Sorts the
results into ascending or descending order
select -Adds the result to the return type
group / by -Groups the results based on a given
key
14
The Evolution of C#
C# 3.0
C# 2.0
C# 1.0
Language Integrated
Query
Generics
Components on a Managed
Runtime
15
Language Enhancement
Implicitly Typed Local Variables
Object Initializers
Anonymous Types
Lambda Expressions
Extension Methods
Query Expressions= LINQ
16
Implicitly Typed Local
Variables
int i = 666;
string s = "Goodbye";
double d = 3.14;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new
Dictionary<int,Order>();
var
var
var
var
var
i = 666;
s = "Goodbye";
d = 3.14;
numbers = new int[] {1, 2, 3};
orders = new Dictionary<int,Order>();
The type on the
right hand side
17
Implicitly Typed Local
Variables
varcan only be used when a local variable is
declared and initialized in the same statement;
the variable cannot be initialized to null, or to a
method group or an anonymous function.
Variables declared by usingvarcannot be
used in the initialization expression.
For Eg: legal: int i = (i = 20);but this
expression produces a compile-time error:var i
= (i = 20);
Multiple implicitly-typed variables cannot be
initialized in the same statement.
18
Object Intializers
Object initializers let you assign values to
any accessible fields or properties of an
object at creation time without having to
invoke a constructor followed by lines of
assignment statements.
19
Object Intializers
class Car
{
public string Name { get; set; }
public Color Color { get; set; }
}
Car car = new Car
{
Name = "Chevrolet Corvette",
Color = Color.Yellow
};
20
Anonymous Type
Anonymous types allow us to create new type
without defining them. This is way to defining read
only properties into a single object without having
to define type explicitly.
varanonymousData =new
{
ForeName ="Jignesh",
SurName ="Trivedi"
};
Console.WriteLine("First Name : "+
anonymousData.ForeName);
21
Lambda Expression
A lambda expression is an anonymous
functionthat you can use to create
delegate.
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.
22
Example
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> elements = new List<int>() { 10, 20, 31, 40 };
// Find index of first odd element.
int oddIndex = elements.FindIndex(x => x % 2 != 0);
Console.WriteLine(oddIndex);
}
}
23
Extension Method
An extension method has simplified calling
syntax.
It represents static methods as instance
methods.
It is astaticmethod.
It must be located in astaticclass.
It uses the "this" keyword as the first
parameter with a type in .NET and this
method will be called by a given type
instance on the client side.
24
Extension Method
It also shown by VS intellisense. When we press the dot (.)
after a type instance, then it comes in VS intellisense.
An extension method should be in the same namespace as it
is used or you need to import the namespace of the class by
ausingstatement.
You can give any name for the class that has an extension
method but the class should bestatic.
If you want to add new methods to a type and you don't
have the source code for it, then the solution is to use and
implement extension methods of that type.
If you create extension methods that have the same
signature methods as the type you are extending, then the
extension methods will never be called.
25
Example
public static class ExtensionMethods
{
public static string UppercaseFirstLetter(this string value)
{
// Uppercase the first letter in the string.
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
26
class Program
{
static void Main()
{
// Use the string extension method on this value.
string value = "dot net perls";
value = value.UppercaseFirstLetter();
Console.WriteLine(value);
}
}
27
LINQ
When people hear about LINQ, they in most
cases think about something like the Entity
Framework, i.e., the possibility to write queries
directly in C# code that will be directly
translated to SQL statements and executed
against the database.
It is important to know that this is not LINQ.
LINQ is a set of C# functions, classes, and
operators that enable developers to execute
queries against a collections of objects. True
LINQ queries are executed against collections.
28
Basic query
LINQ is based on a set of query operators,
defined as extension methods, that work
with any object that implements the
Enumerable<T> or IQueryable<T>
interface.
DEMO
29
Query Keywords
From Clause:
The first keyword is the from clause. It defines the
data source of a query or sub query and a range
variable that defines each single element to query
from the data source.
The data source can be any instance of a type
that implements the interfaces IEnumerable,
IEnumerable<T>, or IQueryable<T> (which
implements IEnumerable<T>).
30
Query Keywords
From Clause:
Queries can have multiple from clauses that
define joins between multiple data sources.
DEMO
31
Query Keywords
Where Clause:
Where clause specifies a filtering condition to
apply to the data source.
Select Clause:
The select clause specifies the shape of the
query output.
32
Standard LINQ Operators
1.
2.
3.
4.
5.
Filtering Operators
Projection Operator
Ordering Operator
Set Operators
Conversion Operators
33
Filtering Operators
Filtering operators basically take a sequence
as input, filter the sequence on the basis of
some condition and returns the filtered
sequence. These operators include:
1. Where
2. Skip
3. Distinct
4. Take
5. TakeWhile
6. SkipWhile
34
Projection Operator
These operators also take a sequence of
collection as an input, perform projection on
the items of the sequence, based on the
predicate passed to it and return back the
projected sequence.
The two major projection operators are:
1. Select
2. SelectMany
35
Ordering Operator
Ordering operators are used to modify the
order of a sequence. It takes an input
sequence, changes the order of the sequence
and returns the sequence back. There are
three ordering operators in LINQ:
1. OrderBy
2. ThenBy
3. Reverse
36
Set Operators
Set operators are sequence to sequence
operators that take two sequences, perform
sum functionality on these sequences and
return the sequence. There are four major set
operators.
1. Union
2. Intersect
3. Concat
4. Except
37
Conversion Operators
LINQ queries can be executed on all those
collection types that implement the
IEnumerable<T> interface.
However, LINQ contain query operators that
can be used one collection into other. There
are two major conversion operators in LINQ.
1. Cast
2. OfType
38
Sequence to Element
Operators
These operators that take a sequence as an input and
return an element based on the functionality of the
operator.
1.
2.
3.
4.
5.
6.
7.
8.
9.
First
Last
Single
ElementAt
FirstOrDefault
LastOrDefault
SingleOrDefault
ElementAtOrDefault
DefaultIfEmpty
39
Aggregation Methods
These operators take sequence of elements as
input and return a scalar value.
Major aggregation operators are:
1.
2.
3.
4.
5.
6.
7.
Count
Min
Max
Average
Sum
LongCount
Aggregate
40
Quantifiers
Quantifiers are types of sequence to
elements operators. Unlike aggregation
operators that returned a single element,
quantifiers return a bool value.
The major operators in LINQ are:
1. Any
2. Contains
3. All
4. SequenceEqual
41
LINQ with Arrays
DEMO
42
LINQ with ArrayList
DEMO
43
LINQ to Generic
DEMO
44
LINQ to Dictionary
DEMO
45
Thanks
For Any Query:
Email: [email protected]
Mob: +91 7030320111
Visit: www.vinsys.com
46