Category Archives: LINQ

What are different methods to write LINQ Query?

There are following three ways to write LINQ Query:

  • 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. Example – The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a where clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word.
    // Query #1.
    List<int> numbers = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    
    // The query variable can also be implicitly typed by using var
    IEnumerable<int> filteringQuery =
        from num in numbers
        where num < 3 || num > 7
        select num;
    
    // Query #2.
    IEnumerable<int> orderingQuery =
        from num in numbers
        where num < 3 || num > 7
        orderby num ascending 
        select num;
    
    // Query #3. 
    string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
    IEnumerable<IGrouping<char, string>> queryFoodGroups =
        from item in groupingQuery
        group item by item[0];
    
  • 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<T> or IQueryable<T>.
    Example – The following example shows a method call in a query expression:

    List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    List<int> numbers2 = new List<int>() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
    // Query #4. 
    double average = numbers1.Average();
    
    // Query #5.
    IEnumerable<int> concatenationQuery = numbers1.Concat(numbers2);
    

    If the method has parameters, these are provided in the form of a lambda expression, as shown in the following example:

    // Query #6.
    IEnumerable<int> largeNumbersQuery = numbers2.Where(c => c > 15);
    

    Each of the previous queries can be written by using implicit typing with var, as shown in the following example:

    // var is used for convenience in these queries 
    var average = numbers1.Average();
    var concatenationQuery = numbers1.Concat(numbers2);
    var largeNumbersQuery = numbers2.Where(c => c > 15);
    
  • Mixed Query and Method Syntax – This example shows how to use method syntax on the results of a query clause. Just enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. In general, however, it is better to use a second variable to store the result of the method call. In this manner, the query is less likely to be confused with the results of the query.
    // Query #7. 
    
    // Using a query expression with method syntax 
    int numCount1 =
        (from num in numbers1
         where num < 3 || num > 7
         select num).Count();
    
    // Better: Create a new variable to store 
    // the method call result
    IEnumerable<int> numbersQuery =
        from num in numbers1
        where num < 3 || num > 7
        select num;
    
    int numCount2 = numbersQuery.Count();
    

    Because Query #7 returns a single value and not a collection, the query executes immediately.
    The previous query can be written by using implicit typing with var, as follows:

    var numCount = (from num in numbers...
    

    It can be written in method syntax as follows:

    var numCount = numbers.Where(n => n < 3 || n > 7).Count();
    

    It can be written by using explicit typing, as follows:

    int numCount = numbers.Where(n => n < 3 || n > 7).Count();
    

What are disadvantages of LINQ?

There are following disadvantages of using LINQ:

  • LINQ is not good to write complex queries like SQL.
  • If you have done some changes in your query, you have to recompile it and redeploy its dll to the server.
  • Small data sets will take longer to build the query than execute.
  • When queries are moved from sql to application side, joins are very slow.
  • DBML concurrency issues.
  • Hard to understand advance queries using Expressions.

What are advantages of LINQ?

There are following advantages of using LINQ:

  • Its Query can be reused.
  • It also allows debugging through .NET debugger.
  • Quick turn around for development.
  • Queries can be dynamically.
  • Tables are automatically created into class.
  • Columns are automatically created into properties.
  • Relationship are automatically appeaded to classes.
  • Lambda expressions are awesome.
  • Data is easy to setup and use.

What are different flavors of LINQ?

There are following four flavors of LINQ:

  1. LINQ to Objects – It enables you to query any in-memory object like as array, collection and generics types. It offers a new way to query objects with many powerful features like filtering, ordering and grouping with minimum code.
  2. LINQ to ADO.NET – LINQ to ADO.NET is used to query data from different databases like as SQL Server, Oracle, and others. Further, it can be divided into three flavours:-
    • LINQ to SQL (DLINQ) – It is specifically designed to work with only SQL Server database. It is an object-relational mapping (ORM) framework that allows 1-1 mapping of SQL Server database to .NET Classes. These classes are automatically created by the wizard based on database table and we can use these classes immediately.
    • LINQ to Datasets – It is an easy and faster way to query data cached in a Dataset object. This allows you to do further data manipulation operations (like searching, filtering, sorting) on Dataset using LINQ Syntax. It can be used to query and manipulate any database (like Oracle, MySQL, DB2 etc.) that can be query with ADO.NET.
    • LINQ to Entities – In many ways, it looks like LINQ to SQL. It is an object-relational mapping (ORM) framework that allows 1-1 mapping , 1-many mapping and many-many mapping of a database to .NET Classes. Unlike LINQ to SQL, it can be used to query any database (like Oracle, MySQL, and DB2 etc.) including SQL Server. Now, it is called ADO.NET Entity Framework.
  3. LINQ to XML (XLINQ) – This allows you to do different operations on XML data source like querying or reading, modifying, manipulating, and saving changes to XML documents. System.Xml.Linq namespace contains classes for LINQ to XML.
  4. Parallel LINQ (PLINQ) – PLINQ was introduced with .NET Framework 4.0. It is a parallel implementation of LINQ to Objects. PLINQ use the power of parallel programming which targets the Task Parallel Library. PLINQ helps you to write a LINQ query which will be execute simultaneously or parallel on different processors.

What is LINQ and why to use it?

LINQ stands for “Language Integrated Query” and pronounced as “LINK“. LINQ was introduced with .NET Framework 3.5 including Visual Studio 2008, C# 3.0 and VB.NET 2008 (VB 9.0). It enables you to query the data from the various data sources like SQL databases, XML documents, ADO.NET Datasets, Web services and any other objects such as Collections, Generics etc. by using a SQL Query like syntax with .NET framework languages like C# and VB.NET.

Why LINQ

LINQ has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET framework languages like C# and VB.NET. This powerful feature helps you to avoid run-time errors.

LINQ also provides a uniform programming model (i.e. common query syntax) to query various data sources. Hence you don’t need to learn the different ways to query different data sources.