What are different methods to write LINQ Query?

There are following three ways to write LINQ Query:

  1. Query Expression (Query Syntax) : Query expression syntax is like as SQL query syntax with just a few minor deviations. The result of a query expression is a query object, which is usually a collection of type IEnumerable<T> or IQueryable<T>. This syntax is easy to read and write and at compile time, query expression is converted into Method Invocation.
    Query Expression Syntax:

    from [identifier]
    in [source collection]
    let [expression]
    where [boolean expression]
    order by [expression(ascending/descending)]
    select [expression]
    group [expression] by [expression]
    into [expression]

    Query Expression Example:

    // Datasource
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Query based syntax
    IEnumerable<int> query = from num in numbers
                             where num > 5 && num < 10
                             select num;
    //result: 6,7,8,9
  2. Method Invocation (Method Syntax) : Method syntax is complex as compared to Query expression since it uses lambda expression to write LINQ query. It is easily understood by .NET CLR. Hence at compile time, Query expression is converted into Method Invocation. The result of a Method syntax is also a query object, which is usually a collection of type IEnumerable or IQueryable.
    Method Invocation Syntax:

    [source collection]
    .Where [boolean expression]
    .OrderBy [expression(ascending/descending)]
    .Select [expression]
    .GroupBy [expression]

    Method Invocation Example:

    // Datasource
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Method based syntax
    IEnumerable<int> query = numbers.Where(num => num > 5 && num < 10);
    //result: 6,7,8,9
  3. Mixed Syntax : You can use a mixture of both syntax by enclosing a query expression inside parentheses and make a call to method.
    // Datasource
    List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    // Mixed syntax
    int query = (from num in numbers
                 where num > 5 && num < 10
                 select num).Count();
    //result: 4

Note: There are no semantic differences (in terms of performance, execution) between Query Syntax and Method Syntax.

Tagged , . Bookmark the permalink.

Leave a Reply