LINQ Queries(Part 2):

Vishwas Bhat - Aug 20 - - Dev Community

LINQ Query Operation

Step 1 : Obtain the Data Source:
A valid LINQ data source must support the IEnumerable interface or an interface that inherits from it.

Let's Define Simple data source:

var EmployeeIds= new int[5] { 0, 1, 2, 3, 4 };
Enter fullscreen mode Exit fullscreen mode

Here The studentIds is an array and it supports the IEnumerable
interface

Types that support IEnumerable or a derived interface (IQueryable) are called queryable types. A queryable type can directly be applied as a LINQ data source. However, if the data source is not represented in memory as a queryable type, we have to use LINQ providers to load it to a queryable form.

Steps 2 :Create the Query
A query specifies what information we want to retrieve from the data source.
To create a query , We need to Import LINQ into our code

using System.Linq;
Enter fullscreen mode Exit fullscreen mode

Now We Will Write a Query:

var EmployeeWithEvenIds =
    from EmployeeId in EmployeeIds
    where (EmployeeId % 2) == 0
    select EmployeeId;
Enter fullscreen mode Exit fullscreen mode

Here We are returning IEnumberable<int> Collection named EmployeeWithEvenIds. It Holds all the Even-numbered Employee Ids.

The query expression has three clauses. The from , where , select

  • from clause describes the data source.
  • where clause applies filters.
  • select clause produces the result of the query by shaping the data. _

Step 3: Execute the Query:
There are two ways to execute a LINQ query:

  • Deferred Execution
  • Immediate Execution

Deferred Execution:
We differ the actual execution of our previous query until we iterate over it using a foreach statement. This concept is called deferred execution or lazy loading:

foreach (int EmployeeId in EmployeeWithEvenIds )
{
    Console.Write("Employee Id {0} which is even.", EmployeeId);
}
Enter fullscreen mode Exit fullscreen mode

Immediate Execution:
Immediate execution is completely the opposite of deferred execution. Here, we execute our query and get the result immediately. Aggregate functions such as Count, Average, Min, Max, Sum, and element operators such as First, Last, SingleToList, ToArray, ToDictionary are some examples.

. . .
Terabox Video Player