Wednesday, 13 January 2016

LINQ

LINQ (Part 1)

Definition: "LINQ(Language Integrated  Query) is a Microsoft programming methodology that adds formal query capabilities into .NET based programming languages".It offers comprehensive syntax for manipulating data .

Why LINQ:

  1. Reduce the Amount of Code.
  2. A better understanding of the intent of what the code is  doing .
  3. A similar set of LINQ queries can be applied on different data sources.
  4. LINQ enables queries as first class citizen in C# and Visual Studio.
The building Blocks of LINQ
There are two fundamental blocks in LINQ
  1. Sequence
  2. Element
A sequence is instance of class that implements IEnumerable<T> interface.A sequence is basically a list of items and each item is treated as element.
There are two types of sequences.
  1. Local
  2. Remote
  • Local Sequence implements IEnumerable <T> interface. 
  • Remote Sequence implements IQueryable<T> interface.
Example of Remote Sequence implements will be discussed later.

Example of Local Sequence:



  Out Put:





















The above example is about a local sequence .Now lets how we can manipulate it very easily with the help of LINQ.

Example:
Write a code that returns only those values which are greater than 2.
Out Put:




















You can see that how we can easily manipulate data and can get result according to our requirements.
Another important feature of LINQ is Deferred Execution.
Deferred Execution:
It means that the execution of LINQ query does not execute at the time of creation. Rather it is executed when it is used.
Actually the execution of LINQ query starts with the foreach loop.
Example:
Out Put:


















Notice that result 99 has been included even at that time the query was constructed.
There are numbers of operators that runs at the time of query creation like ToArray, ToDictionery etc.
Example:
Out Put:

















Notice that 99 is not included,because of additional ToArray().


No comments:

Post a Comment