LINQ: A Introduction: Speaker: Arvind Kumar
LINQ: A Introduction: Speaker: Arvind Kumar
Agenda
What is LINQ
LINQ Architecture
What is LINQ?
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
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
13
LINQ Syntax
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
16
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
Object Intializers
19
Object Intializers
class Car
{
public string Name { get; set; }
public Color Color { get; set; }
}
20
Anonymous Type
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
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
Basic query
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
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
DEMO
42
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