You are on page 1of 44

The Basics

of LINQ

July 26, 2019 ASP.NET MVC 5 TRAINING


GOOD
DAY!
I am CARL STEPHEN YMARI LAREDO. I am about to share my
knowledge about the basics of LINQ and how to implement it in
ASP.Net MVC 5.

ASP.NET MVC 5 TRAINING


What is a Query?
— A database query is a request for data or information from a database
table or from the combination of tables. The most well-known and widely-
used query language is the SQL (Structured Query Language). SQL is the
standard language for relational database management systems according
to ANSI (American National Standards Institute).

ASP.NET MVC 5 TRAINING


Examples of Query (SQL)

Examples:
//Selecting all data from Table Students
— SELECT * FROM Students;
or SELECT Id, Age FROM Students;

//Inserting a new student from Table Students


— INSERT INTO Students(FirstName, LastName, Age)
VALUES (“Tony”, “Stark”, “20”);

//Updating a row from Table Students Where Id is equals to 1


— UPDATE Students SET FirstName=“Steve”, LastName=“Rogers”
WHERE Id = 1;

//Delete a row from Table Students Where Id is equals to 2


— DELETE FROM Students WHERE Id = 2;
ASP.NET MVC 5 TRAINING
What
is LINQ?
ASP.NET MVC 5 TRAINING
What is LINQ?

— LINQ or Language-Integrated Query is a


powerful query language designed by Anders
Hejlsberg. It was introduced along with .Net
3.5 and Visual Studio 2008. LINQ can also be
used with C# or Visual Basic to query different
data sources.

ASP.NET MVC 5 TRAINING


Anders
Hejlsberg
He was the original author
of Turbo Pascal and the
chief architect of Delphi.
He currently works for
Microsoft as the lead
architect of C# and core
developer on TypeScript.

ASP.NET MVC 5 TRAINING


Basic LINQ Query Operation

Three Parts of Query Operation:

 Obtaining the Data Source.

 Creating the query.

 Executing the created query.

ASP.NET MVC 5 TRAINING


Basic LINQ Query Operation

Example of the query operation:


// Obtain Data Source.
int[] collection = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

//  Create the query.


var numQuery = from num in collection
where (num % 2) == 0 select num;
// Execute the query.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}

ASP.NET MVC 5 TRAINING


Examples of LINQ
(SQL to LINQ)

Examples:
//Selecting all columns from Table Students
— SELECT * FROM Students ORDER BY Id DESC;
_context.Students.OrderByDescending(x => x.Id).ToList();

//Inserting new student from Table Students


— INSERT INTO Students(FirstName, LastName, Age)
VALUES (“Tony”, “Stark”, “20”);
_ context.Students.Add(model);

//Updating a row from Table Students Where Id is equals to 1


— UPDATE Students SET FirstName=“Steve”, LastName=“Rogers”
WHERE Id = 1;
_ context.Entry(model).State = EntityState.Modified;

//Deleting a row from Table Students Where Id is equals to 2


— DELETE FROM Students WHERE Id = 2;
_ context.Students.Remove(model);

ASP.NET MVC 5 TRAINING


Why
Use LINQ?
— LINQ makes the code more compact and readable and
it can also be used to query different data sources. Using
LINQ is more productive and enhances the performance of
the program.
ASP.NET MVC 5 TRAINING
How LINQ Benefits the Developer?

• You do not need to learn a new language as it is similar to


SQL and C# Languages.

• LINQ is simple and also neat.

• VS Studio provides IntelliSense support for your range


variable as you type in the rest of the LINQ statement.

• LINQ is type safe, so query errors are type checked at


compile time rather than the old way of finding mistakes
in query during the run-time. In short, it makes the
process of debugging faster.

• Reduces the amount of code you have to write, which


gives you better performance in coding.
ASP.NET MVC 5 TRAINING
Example: Why Use LINQ?

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 } , };

ASP.NET MVC 5 TRAINING


Example: Why Use LINQ?
Find Item Based on Name In The Array

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 } , };

Without Using LINQ: Using LINQ:


List<string> prodNames= new List<string>(); Product prodNames = items.Where(s =>
s.ItemName == “Nagaraya ").ToList();
foreach(Product prod in items)
{
if(prod.ItemName == “Nagaraya”)
{
prodNames.Add(prod.ItemName);
}
}
ASP.NET MVC 5 TRAINING
Example: Why Use LINQ?
Find Items Between 15 and 30 In The Array

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 } , };

Without Using LINQ: Using LINQ:


Product[] itemsList = new Product[5];
int i = 0; Product[] items = items.Where(s => s.Pieces > 15
&& s.Pieces < 30).ToArray();
foreach (Product prod in items) {
if (prod.Pieces > 15 && prod.Pieces < 30)
{
itemsList[i] = prod;
i++;
}
}
ASP.NET MVC 5 TRAINING
Advantages of Using LINQ

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.

It provides type checking of objects at compile time.

LINQ provides IntelliSense for generic collections

ASP.NET MVC 5 TRAINING


Basic LINQ Query
Operations
ASP.NET MVC 5 TRAINING
LINQ Query Operations

Obtaining Data Source


Filtering
Ordering
Grouping

ASP.NET MVC 5 TRAINING


Obtaining a Data Source

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.

ASP.NET MVC 5 TRAINING


Filtering

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.

— You can user && sign and || sign when filtering.

ASP.NET MVC 5 TRAINING


Ordering

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.

ASP.NET MVC 5 TRAINING


Grouping

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.

ASP.NET MVC 5 TRAINING


LINQ API
ASP.NET MVC 5 TRAINING
IQueryable<T> Interface Class

— Is an interface that is useful when we want to iterate a


collection of objects which deals with ad-hoc queries against
the data source or remote database, like SQL Server. This
interface exists in System.Linq namespace and is inherited
from IEnumerable .

— IQueryable is best suitable for LINQ to SQL Conversion and


executes a query on a server with all filter conditions on server-
side and gets the records which are matching with the filter
condition.

ASP.NET MVC 5 TRAINING


IEnumerable<T> Interface Class

— Is an interface that is useful when we want to iterate the


collection of objects which deals with in-process memory. It is
suitable for querying data from in-memory collections like List,
Array and so on. This interface exists in the System.Collections
namespace.

— IEnumerable filters did not execute on the server side and it


fetched all the records which are matching all conditions.

ASP.NET MVC 5 TRAINING


IList<T> Interface Class

— Is an interface that is useful when we want to perform any


operation like Add, Remove or Get item at specific index
position in the collection. It is a generic collection which resides
in System.Collections.Generic namespace.

— IList extends ICollection. It can perform all operations


combined from IEnumerable and ICollection, and some more
operations like inserting or removing an element in the middle
of a list.

ASP.NET MVC 5 TRAINING


Difference Between Classes
IEnumerable<T> v. IQueryable<T> Interfaces

Basis IEnumerable<T> IQueryable<T>

Namespace System.Collections System.Linq

Derivation There is no base interface Derives the base interface


from IEnumerable
Deferred Execution Supported Not Supported

Lazy Loading Not Supported Supported

Queries in-memory queries out-memory (server-side) queries

Custom Query Not Supported Supported

Deferred execution — means that the evaluation of an expression is delayed until


its realized value is actually required.

ASP.NET MVC 5 TRAINING


LINQ Query
Behaviors

ASP.NET MVC 5 TRAINING


LINQ Query Behaviors

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.

ASP.NET MVC 5 TRAINING


Deferred 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; } };
} //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

ASP.NET MVC 5 TRAINING


Deferred Query Execution
(Example)

Created Query Variable


public static void Main(string[] args)
{
var studList = new List< Student >{
new Student{Id = 1, Name = “Stephen”, Age = 18},
new Student{Id = 2, Name = “James”, Age = 15},
new Student{Id = 3, Name = “Marie”, Age = 14},
new Student{Id = 4, Name = “Johnson”, Age = 20}
};

var list = studList.Where(x => x.Age > 15);

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

ASP.NET MVC 5 TRAINING


Immediate
Query Execution
— Immediate execution is the reverse of deferred execution. It forces the LINQ query to
execute and gets the result immediately.

— 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

ASP.NET MVC 5 TRAINING


Immediate Query Execution
(Example)

Added an aggregate function


public static void Main(string[] args) Count() in the query variable
{ which will return a singleton
var studList = new List< Student >{ value.
new Student{Id = 1, Name = “Stephen”, Age = 18},
new Student{Id = 2, Name = “James”, Age = 15},
new Student{Id = 3, Name = “Marie”, Age = 14},
new Student{Id = 4, Name = “Johnson”, Age = 20}
};

var list = studList.Where(x => x.Age > 15).Count();

studList.Add(new Student{Id = 5, Name = “Annie”, Age = 21}); Adding a new student to the list.

Console.WriteLine(“No. of Students whose age is above 15: {0}”, list);


}
——————————————————————————————————
OUTPUT:
No. of Students whose age is above 15: 2
The output showed that it counted
only 2 students because the aggregate
function Count() forces the linq query
to execute thus getting the result
immediately.

ASP.NET MVC 5 TRAINING


Deferred vs. Immediate Query
Execution

Deferred/Lazy Operators Immediate/Greedy Operators

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

ASP.NET MVC 5 TRAINING


LINQ
Syntaxes

ASP.NET MVC 5 TRAINING


LINQ Syntaxes

Query Syntax (Comprehension)

Lambda Syntax
(Method)

ASP.NET MVC 5 TRAINING


Query (Comprehension) Syntax

LINQ Query Syntax:


from <range variable> in <IEnumerable<T> or IQueryable<T> Collection>

<Standard Query Operators> <lambda expression>

<select or groupBy operator> <result formation>

POINTS TO REMEMBER:

 Query Syntax is like an SQL (Structure Query Language) syntax.

 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.

ASP.NET MVC 5 TRAINING


Query (Comprehension) Syntax
Example Usage

IList<Product> itemsList = new List<Product> () {


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 } , };

Query Syntax Example:


//Sample LINQ Query Syntax to get items where the no. of an item is between 15 to 30
var result = from s in itemsList where s.Pieces > 15 && s.Pieces < 30 select s;

Sample result:
Nova
Piatos
Nagaraya

ASP.NET MVC 5 TRAINING


Lambda (Method) Syntax

Lambda (Method) Syntax (also known as


fluent syntax) uses extension methods
included in the Enumerable or Queryable
static class, similar to how you would call
the extension method of any class.
POINTS TO REMEMBER:

 LINQ Method Syntax aka Fluent syntax because it allows series of


extension methods call.

 Implicitly typed variable - var can be used to hold the result of the LINQ
query.

ASP.NET MVC 5 TRAINING


Lambda (Method) Syntax
Example Usage

IList<Product> itemsList = new List<Product> () {


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 } , };

Query Syntax Example:


//Sample LINQ Method Syntax to get items where the no. of an item is between 15 to
30
var result = itemsList.Where(x => x.Pieces > 15 && x.Pieces < 30).ToList();
Sample result:
Nova
Piatos
Nagaraya

ASP.NET MVC 5 TRAINING


Summary

Database Query is designed to retrieve specific


results from the database.
Example of relational database management
systems are MS Access, MS SQL Server, Sybase,
Oracle, etc.
Most commonly used query language is SQL.
In a nutshell, LINQ allows you to write your queries
directly into your code.

ASP.NET MVC 5 TRAINING


THANK YOU!

You might also like