Professional Documents
Culture Documents
of LINQ
Examples:
//Selecting all data from Table Students
— SELECT * FROM Students;
or SELECT Id, Age FROM Students;
Examples:
//Selecting all columns from Table Students
— SELECT * FROM Students ORDER BY Id DESC;
_context.Students.OrderByDescending(x => x.Id).ToList();
Example Data:
Product[] items = {
new Product() {Id = 1, ItemName = “Nova”, Pieces = 25 } ,
new Product() {Id = 2, ItemName = “Piatos”, Pieces = 16 } ,
new Product() {Id = 3, ItemName = “Nagaraya”, Pieces = 30 } ,
new Product() {Id = 4, ItemName = “Loaded”, Pieces = 43 } ,
new Product() {Id = 5, ItemName = “Oishi”, Pieces = 50 } , };
Example Array:
Product[] items = {
new Product() {Id = 1, ItemName = “Nova”, Pieces = 25 } ,
new Product() {Id = 2, ItemName = “Piatos”, Pieces = 16 } ,
new Product() {Id = 3, ItemName = “Nagaraya”, Pieces = 30 } ,
new Product() {Id = 4, ItemName = “Loaded”, Pieces = 43 } ,
new Product() {Id = 5, ItemName = “Oishi”, Pieces = 50 } , };
Example Array:
Product[] items = {
new Product() {Id = 1, ItemName = “Nova”, Pieces = 25 } ,
new Product() {Id = 2, ItemName = “Piatos”, Pieces = 16 } ,
new Product() {Id = 3, ItemName = “Nagaraya”, Pieces = 30 } ,
new Product() {Id = 4, ItemName = “Loaded”, Pieces = 43 } ,
new Product() {Id = 5, ItemName = “Oishi”, Pieces = 50 } , };
Writing codes is quite faster in LINQ and thus development time also gets reduced
significantly.
Developers don’t have to learn a new query language for each type of data source or data
format.
LINQ makes the code more readable so other developers can easily understand and maintain
it.
The same LINQ syntax can be used to query multiple data sources.
Example #1:
//data is an IEnumerable<Students>
var data = from stud in Students select stud;
Example #2:
//data is an IEnumerable<Students>
var data = _context.Students.ToList();
— In a LINQ query, the first step is to specify the data source. In C# as in most
programming languages a variable must be declared before it can be used. In a LINQ
query, the from clause comes first in order to introduce the data source and the range
variable. The range variable is like the iteration variable in a foreach loop except that no
actual iteration occurs in a query expression.
Example #1:
//return student/s whose last name is Dela Cruz
var data = from stud in Students where s.LastName ==“Dela Cruz” select stud;
Example #2:
//return student/s whose last name is Dela Cruz
var data = _context.Students.Where(x => x.LastName == “Dela Cruz”).ToList();
— The most common query operation in LINQ is to apply a filter in the form of a Boolean
expression. The filter causes the query to return only those elements for which the
expression is true. The result is produced by using the where clause. The filter in effect
specifies which elements to exclude from the source sequence.
Example #1:
//return student/s whose last name is Dela Cruz and sorted in descending order based on Id
var data = from stud in Students where stud.LastName ==“Dela Cruz”
orderby stud.Id descending select stud;
Example #2:
//return student/s whose last name is Dela Cruz and sorted in descending order based on Id
var data = _context.Students.Where(x => x.LastName == “Dela Cruz”)
.OrderByDescending(y => y.Id).ToList();
— Often it is convenient to sort the returned data. The orderby clause will cause the
elements in the returned sequence to be sorted according to the default comparer for the
type being sorted.
Example #1:
//return group of student/s based on Age
var data = from stud in Students group stud by stud.Age;
Example #2:
//return group of student/s based on Age
var data = _context.Students.GroupBy(x => x.Age);
— The group clause enables you to group your results based on a key that you specify. For
example you could specify that the results should be grouped by the Age so that all
Students are in individual groups. When you end a query with a group clause, your results
take the form of a list of lists. In iterating the result of the query you must you nested
foreach loop.
Deferred Query
Execution
Immediate Query
Execution
ASP.NET MVC 5 TRAINING
Deferred
Query Execution
— By default, LINQ uses deferred execution. When we write a LINQ query, it
doesn’t execute by itself. It executes only when we are accessing the query
results. Deferred execution means that the evaluation of an expression is
delayed until its realized value is actually required. It greatly improves
performance by avoiding unnecessary execution.
Base Class:
Example: public static void Main(string[] args)
//Student Model {
Public class Student var studList = new List< Student >{
{ new Student{Id = 1, Name = “Stephen”, Age = 18},
public int Id { get; set; } new Student{Id = 1, Name = “James”, Age = 15},
new Student{Id = 1, Name = “Marie”, Age = 14},
public string Name { get; set; }
new Student{Id = 1, Name = “Johnson”, Age = 20}
public int Age { get; set; } };
} //Created Query
var list = studList.Where(x => x.Age > 15);
//Iteration of List
foreach (var stud in list)
{
Console.WriteLine(“Student Name: {0}”, stud.Name);
}
}
—————————————————————————————
OUTPUT:
Student Name: Stephen
Student Name: Johnson
studList.Add(new Student{Id = 5, Name = “Annie”, Age = 21}); Adding a new student to the list.
foreach (var stud in list)
{
Console.WriteLine(“Student Name: {0}”, stud.Name);
} The process was deferred until the query
} variable was iterated over in a foreach
———————————————————————————————— loop.
OUTPUT:
Student Name: Stephen
Student Name: Johnson
Student Name: Annie
— To force immediate execution of a query that return a singleton value, we can use
the aggregate operators or element operators. (e.g. Count(), Max(),First(),Average())
— To force immediate execution of a query that does not return a singleton value, we
can call the ToList method, the ToDictionary method, or the ToArray method on a query
or query variable.
ASP.NET MVC 5 TRAINING
Immediate Query Execution
(Example)
Base Class:
Example: public static void Main(string[] args)
//Student Model {
Public class Student var studList = new List< Student >{
{ new Student{Id = 1, Name = “Stephen”, Age = 18},
public int Id { get; set; } new Student{Id = 1, Name = “James”, Age = 15},
new Student{Id = 1, Name = “Marie”, Age = 14},
public string Name { get; set; }
new Student{Id = 1, Name = “Johnson”, Age = 20}
public int Age { get; set; } };
}
var list = studList.Where(x => x.Age > 15);
int x = 0;
foreach (var stud in list)
{
x++;
}
Console.WriteLine(“No. of Students: {0}”, x);
}
—————————————————————————————
OUTPUT:
No. of Students: 2
studList.Add(new Student{Id = 5, Name = “Annie”, Age = 21}); Adding a new student to the list.
Query is not executed at the point of its declaration Query is executed at the point of its declaration
Projection Operator – Select, SelectMany Aggregate Functions – Count, Average, Min, Max,
Restriction Operator – WherePaging Operator – Take, Sum
Skip Element Operators – First, Last, SingleToList, ToArray,
ToDictionary
Lambda Syntax
(Method)
POINTS TO REMEMBER:
It always starts with from clause and can be end with Select or GroupBy clause.
It uses various other operators like filtering, joining, grouping, sorting operators to
construct the desired result.
Implicitly typed variable - var can be used to hold the result of the LINQ query.
Sample result:
Nova
Piatos
Nagaraya
Implicitly typed variable - var can be used to hold the result of the LINQ
query.