You are on page 1of 45

University of Computer Studies

Chapter (7)
LINQ ( Language Integrated Query )

1
Contents

 What is LINQ?
 Query Syntax
 Operators in Query Syntax
 Operators in Method Syntax

2
LINQ ( Language Integrated Query )
 It is a data retrieval mechanism.

 It provides querying capabilities to . NET languages with a syntax similar to a SQL.

 It is used to filter, select and group data in various data structures such as array, list, collections, ADO.Net DataSet,
XML Docs, web service and MS SQL Server and other databases.

 LINQ queries return results as objects.

Execute Query
Returns Data
Objects { Linq Query} Source
Retrieve Result

3
LINQ ( Language Integrated Query )

The standard LINQ tools are divided into the following three broad categories:
LINQ to Objects LINQ methods that interact with C# objects such as arrays, dictionaries, and lists.

LINQ features that read and write XML data.


LINQ to XML
LINQ lets you easily move data between XML hierarchies and other C# objects.

LINQ to ADO.NET LINQ features that let you write LINQ-style queries to extract data from relational databases

All LINQ query operations consist of three distinct actions:


Obtain the data source
Create the query
Execute the query 4
LINQ ( Language Integrated Query )

1. Query Syntax
2. Method Syntax

 Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using
the LINQ declarative query syntax.
 Query syntax must be translated into method calls for the .NET common language runtime (CLR)
when the code is compiled.
 These method calls invoke the standard query operators, which have names such as Where, Select,
GroupBy, Join, Max, and Average.
 Standard query operators can be called directly by using method syntax instead of query syntax.

5
6
Query Syntax

var variablename = from queryVariable in dataSource


where……
orderby…..
select …..

7
Query Syntax

class Student
{
public int StudentID;
public string StudentName;
public int Age;
public string year;
public string Interested;
}

8
Query Syntax
ArrayList std = new ArrayList() {
new Student() { StudentID = 1, StudentName = "Su Su", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Yu Yu", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Ma Ma", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Aung Aung" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Kyaw Kyaw" , Age = 15 },
new Student() { StudentID = 6, StudentName = "Ei Ei" , Age = 15 },
new Student() { StudentID = 7, StudentName = "Pa Pa" , Age = 15 }
};

ArrayList detail = new ArrayList() {


new Student() { StudentID = 1, year = "First Year", Interested = “Programming”} ,
new Student() { StudentID = 2, year = " Third Year ", Interested = “Database” } ,
new Student() { StudentID = 3, year = " Second Year ", Interested = “Web Design” } ,
new Student() { StudentID = 4, year = " Third Year " , Interested = “DataMining”} ,
new Student() { StudentID = 5, year = " Fifth Year " , Interested = “Data Science” }
9
};
From in Query Syntax
from clause The from clause tells where the query should get the data.

select clause Lists the fields that the query should select into its result.

Syntax
from ....in var variablename = from queryVariable in dataSource
select … ;
select …..

Example
var result = from s in std
select s.StudentName;

10
From in Query Syntax

If you want to select more than one field from the query’s objects,
Select new clause
use the new keywords followed by the values enclosed in braces.

Syntax

var variablename = from queryVariable in dataSource


from ....in
select new {…..,……..};
select new{ … ,….};

Example

var result = from s in std


select new { s.StudentName, s.Interested};

11
From in Query Syntax
Syntax

from ....in var variablename = from queryVariable1 in dataSource1


from….in from queryVariable2 in dataSource2
select new{ … ,….}; select new {….. , ……..};

Example
var result = from s in std
from d in detail
select new { s.StudentName, d.Interested };

12
Where in Query Syntax

Where clause Filters the records selected by the from clause.

Syntax

from ... ..in var variablename = from queryVariable in


where ... dataSource
select … where…..
select …….

Example
var result = from s in std var result = from s in std
where s.Age > 12 && s.Age < 20 from d in detail
select s.StudentName; where s.studentID == d.studentID
select new { s.StudentName, d.Interested };

13
Orderby in Query Syntax

Orderby clause Sorts a query’s results. Usually the values used to sort the results are properties of the objects selected.

Syntax

var variablename = from queryVariable in dataSource


from ... .. in
orderby…..
orderby…descending
select …..
select ….

Example
var Result = from s in std var Result = from s in std
orderby s.StudentName orderby s.StudentName descending
select s.StudentName; select s.StudentName;

14
Join in Query Syntax
Join clause selects data from multiple data matching up corresponding field

Syntax

from ... in var variablename = from ... in outerDataSource

join ... in join ... in innerDataSource

on outerKey equals innerKey on outerKey equals innerKey

select ... select ...

foreach (var q in result)


Example
{
var result = from Student s in std
join Student d in detail Console.WriteLine("Name: " +q.StudentName
on s.StudentID equals d.StudentID
+ ", Year: " + q.year
select new { s.StudentName, d.year, d.Interested };
+ ", Interested: " + q.Interested);
} 15
GroupJoin in Query Syntax

Join into clause add an “ into ” clause to the join clause to group the joined values into a list with a specified new
name.

Syntax

var variableName = from ... in outerSequence


from ... in
join ... in innerSequence
join ... in
on outerKey equals innerKey
on ………….
into groupedCollection
into ……..
select ...
select ...

16
GroupJoin in Query Syntax
Example

var result = from Student s in std

join Student d in detail

on s.StudentID equals d.StudentID into studentGroup

select new { gp = studentGroup }

foreach (var q in result)

foreach (var sd in q.gp)

Console.WriteLine("ID: "+ sd.StudentID+", Year: "+sd.year+", Interested="+ sd.Interested);

}
17
GroupBy in Query syntax

group by clause Like join into, group by enables a program to gather related values together into groups.

Syntax

from ... in
from ....in
1. group….. by…..into ……..
group ….by… select ...

from ....in
2. where..
group ….by…

from ....in
3. where..
order by … descending
18
group ….by…
GroupBy in Query syntax
1. var variabaleName = from queryVariable in dataSource
group queryVariable by queryVariable.Key;

2. var variableName = from queryVariable in dataSource


group queryVariable by queryVariable.Key
into groupedCollection
select

3. var variabaleName = from queryVariable in dataSource


where…………
group queryVariable by queryVariable.Key;

4. var variabaleName = from queryVariable in dataSource


where…………
orderby……..descending
group queryVariable by queryVariable.Key; 19
GroupBy in Query syntax
Example 1
var groupedResult = from Student s in std
group s by s.Age;

foreach (var ageGroup in groupedResult) // to loop group


{
Console.WriteLine("Age Group:" + ageGroup.Key); //Each group has a key

foreach (Student s in ageGroup) // Each group has inner collection // to loop each object in group
{
Console.WriteLine("Student Name: " + s.StudentName);
}

20
GroupBy in Query syntax
Example 2
var result = from Student s in std
group s by s.Age into StudentGp
select new { StudentAge = StudentGp.Key, Students = StudentGp };

foreach (var group in result)


{
Console.WriteLine("Customer " + group.StudentAge + ":");
foreach (Student ss in group.Students)
{
Console.WriteLine(" Student: " + ss.StudentID+", " + ss.StudentName);
}
}

21
GroupBy in Query syntax
Example 3
var result = from Student s in std
where s.Age > 18
group s by s.Age;

foreach (var group in result)


{
Console.WriteLine("Customer " + group.Key + ":");
foreach (Student ss in group)
{
Console.WriteLine(" Student: " + ss.StudentID + ", " + ss.StudentName);
}
}

22
GroupBy in Query syntax
Example 4
var result2 = from Student s in std
where s.Age > 18
orderby s.Age
group s by s.Age;

foreach (var group in result2)


{

Console.WriteLine("Customer " + group.Key + ":");

foreach (Student ss in group)

Console.WriteLine(" Student: " + ss.StudentID + ", " + ss.StudentName);

}
} 23
24
OfType in Method Syntax
Example
ArrayList mixedList = new ArrayList();
mixedList.Add(0);
mixedList.Add("One");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(new Student() { StudentID = 1, StudentName = "Su Su", Age=20 });

Query Syntax Method Syntax

var result1 = from string s in mixedList.OfType<string>() var result1 = mixedList.OfType<string>();


select s;

foreach (var q in result1)


{ Console.WriteLine(q); }

25
Select in Method Syntax
Example

Query Syntax var result1 = from Student s in std


select new { s.StudentName, s.Age };

Method Syntax var result = std.Select ( x => new { x.StudentName, x.Age });

foreach (var q in result)


{
Console.WriteLine("Name: " + q.StudentName + ", Age: " + q.Age);
}
26
Where in Method Syntax
Example
List<string> subj = new List<string>() { "C# Tutorials", "VB.NET Tutorials", "Learn C++", "MVC Tutorials" ,
"Java" };

var result = from Student s in std


Query Syntax where s.Age > 12 && s.Age < 20
select s;

Method Syntax var result = std.Where(s => s.Age > 12 && s.Age < 20)

foreach (var q in result)


{
Console.WriteLine(q.StudentName);
27
}
Orderby in Method Syntax
Example

var result = from Student s in std


Query Syntax orderby s.StudentName descending
select s.StudentName ;

var result = std.OrderBy(s => s.StudentName);


Method Syntax
var result= std.OrderByDescending(s => s.StudentName);

foreach (var q in result)


{
Console.WriteLine(q.StudentName);
}

28
Orderby in Method Syntax
Example

var result = std.OrderBy(s => s.StudentName).ThenBy(s=>s.Age);

Method Syntax

var result = std.OrderBy(s => s.StudentName).ThenByDescending(s => s.Age);

foreach (var q in result)


{
Console.WriteLine(q.StudentName + ", " + q.Age);
}

29
GroupBy in Method syntax
Example
var result = from Student s in std
Query Syntax group s by s.Age;

Method Syntax var result = std.GroupBy(s => s.Age);

foreach (var gp in result) // iterate groups


{
Console.WriteLine("Group Key: " + gp.Key);
foreach (Student t in gp) // iterate all objects in each group
{
Console.WriteLine("Name: " + t.StudentName);
}
30
}
ToLookup in Method Syntax
Example

Query Syntax var result = std.ToLookup(s => s.Age);

foreach (var gp in result) // iterate groups


{
Console.WriteLine("Group Key: " + gp.Key);

foreach (Student t in gp) // iterate all objects in each group


{
Console.WriteLine("Name: " + t.StudentName);
}

} 31
Join in Method syntax
Example
var result = from Student s in std
Query Syntax join Student d in detail
on s.StudentID equals d.StudentID
select new { s.StudentName, d.year, d.Interested };

Method Syntax var result2 = std.Join(detail,


s => s.StudentID,
d => d.StudentID,
(s, d) => new { s.StudentName, d.year, d.Interested });

foreach (var q in result2)


{
Console.WriteLine("Name: " + q.StudentName + ", Year: " + q.year + ", Interested: " + q.Interested);
}
32
Join in Method syntax
Example
List<string> day1 = new List<string>() { "Monday", "Tuesday", "Thursday", "Saturday", "Sunday" };
List<string> day2 = new List<string>() { "Friday", "Sunday", "Monday", "Wednesday", "Tuesday" };

Query Syntax Method Syntax

var result = from string st1 in day1 var result = day1.Join ( day2,
join string st2 in day2 st1=>st1,
on st1 equals st2 st2=>st2,
select st1; ( st1, st2 )=>st1 );

foreach (var q in result)


{
Console.WriteLine(q);
33
}
All, Any, Contains operators in Method Syntax

All Operator bool result = std.All(s => s.Age > 12 && s.Age < 20);

Any Operator bool result = std.Any(s => s.Age >12 && s.Age< 20);

List<int> num = new List<int>() { 10, 20, 30, 40, 50 };

Contains Operator bool result = num.Contains(100);

34
Aggregate operator in Method Syntax

string result= std.Aggregate<Student,string>(


"Student Names: ",
(str,s) => str +s.StudentName+" , "

);

List<string> day1 = new List<string>() { "Monday", "Tuesday", "Thursday", "Saturday", "Sunday" };

string result = day1.Aggregate((d1, d2) => d1 + " || " + d2);

35
Sum in Method Syntax
List<int> num = new List<int>() {10,20,22,55,48,93,70 };

int result = num.Sum(); int totalAge = std.Sum(s=>s.Age);

int result2 = num.Sum(x => int totalAge1 = std.Sum(s =>


{ {
if (x %2==0) if (s.Age < 20)
return x;
else return s.Age;
return 0; else
} return 0;
);
});
36
Average in Method Syntax
Example

List<int> num = new List<int>() { 10, 20, 30 };

double avg = num.Average();

double ageAvg = std.Average(s => s.Age);

37
Count in Method Syntax
Example

List<int> num = new List<int>() { 10, 21, 30 };

int totalElements = num.Count();

int evenNum = num.Count(i => i % 2 == 0);

int x = num.Count(i => i>10 );

38
Count in Method Syntax
Example

int num = std.Count();

int num1 = std.Count(s=> s.Age<20);

int num3 = (from Student s in std


select s).Count();

int num4 = (from Student s in std


where s.Age<20
select s).Count();
39
Max, Min in Method Syntax
Example
List<int> num = new List<int>() { 10, 21, 30,33,40,50,51,201,4,3,7 };

int maxNum = num.Max(); int maxNum = num.Min();

double age = std.Max(s => s.Age); double age = std.Min(s => s.Age);

string st = std.Max(s => s.StudentName); string st = std.Min(s => s.StudentName);

40
Distinct in Method Syntax
Example

List<string> name = new List<string>() { "Su Su", "Ma Ma", "Kyaw Kyaw", "Su Su", "Aung Aung", "Ma Ma", "Hla Hla" };

var dname = name.Distinct();

foreach (var s1 in dname)


Console.Write(s1 + ", ");

41
Union, Intersect in Method Syntax
Example

List<string> day1 = new List<string>() { "Monday", "Tuesday", "Thursday", "Saturday", "Sunday" };


List<string> day2 = new List<string>() { "Friday", "SUNDAY", "Monday", "Wednesday", "TUESDAY" };

var result = day1.Union(day2); var result = day1.Intersect(day2);

foreach (string d in result) foreach (string d in result)


{ {
Console.Write(d + " , ");
Console.Write(d + " , ");
}
}
42
Concat in Method Syntax
Example

List<string> day1 = new List<string>() { "Monday", "Tuesday", "Thursday", "Saturday", "Sunday" };


List<string> day2 = new List<string>() { "Friday", "SUNDAY", "Monday", "Wednesday", "TUESDAY" };

var st = day1.Concat(day2);

foreach (var d in st)


{
Console.Write(d + " , ");
}

43
ElementAt, ElementAtOrDefault
in Method Syntax
Example
List<string> day1 = new List<string>() { "Monday", null, "Thursday" };
List<int> num1 = new List<int>() { 10, 20, 50 };
List<double> d = new List<double>();

day1.ElementAt(0) day1.ElementAtOrDefault(3)

num1.ElementAt(2) num1.ElementAtOrDefault(3)

d.ElementAtOrDefault(0)
44
Thank You

45

You might also like