Wednesday, April 15, 2020

LINQ




  • It stands for Language Integrated Query
  • It is a uniform query syntax in C# to retrieve data from different sources and formats.
  • It is integrated into C# or VB, hence eliminating mismatch between programming language and database as well as providing a single query interface for different type of data source.



  • The LINQ query returns as an Object. It enables you to use an object-oriented approach on a result set and not worry about different result formats.
  • Why LINQ?
    • Familiar language: Developers don’t have to learn a new query language for each type of data source or data format.
    • Less coding: It reduces the amount of code to be written as compared with a more traditional approach.
    • Readable code: LINQ makes the code more readable, so other developers can easily understand and maintain it.
    • IntelliSense Support: LINQ provides IntelliSense for generic collections.
    • Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources.
  • LINQ Query Syntax:  There are two ways to write LINQ queries to IEnumerable collection or IQueryable data sources.
    • Query Syntax or Query Expression Syntax
      • It is similar to SQL queries.
      • Its syntax start with "From" keyword and ends with "Select" keyword or "Group" clause.
      • Use various other operator's like filtering, joining, grouping, sorting operators to construct the desired result.
    • Method Syntax or Method Extension Syntax.
      • It uses extension methods included in the Enumerable or Queryable static class, similar to how you would call the extension method of any class.
      • Method syntax comprises of extension methods and Lambda expression.
      • It allows a series of extension method call.

LINQ provides many extension methods for filtering, grouping, sorting and many more. Following are some extension methods.

Projection Operator 
  • SELECT: Select operator is used to get the value from collection and it can be formatted in the custom result set as per requirement.
  • SELECTMANY: SelectMany operator is used to get the value from the Collection of collection.
Filtering Operator 
  • WHERE: Where is a filter operator in LINQ. It is used for filtering collection based on some criteria.
  •  OFType:  It is used to filter collection based on given Type.

Grouping Operator 
  •  GroupBy: It is used for grouping data based on a key value.
  • ToLookup: It is same as GroupBy but the only difference is ToLookup execution is immediate.

Sorting Operator 
  •  OrderBy: It is used for sorting collection based on a specified field in ascending order.
  • ThenBy: It is used for the second level of sorting in ascending order.
  • OrderByDescending: It is used for sorting collection based on a specified field in descending order.
  • ThenByDescending: It is used for the second level of sorting in descending order.