Theme-Logo
  •   .Net
    •   C Sharp(C#)
    •   Web API
    •   Micro Services
    •   ASP.Net
    • ASP.Net MVC
    • .Net Core
  •   Database
    • SQL Server
    • Oracle
    • PostgreSQL
  •   jQuery
    • jQuery Tutorials
    • jQuery Plugins
    • jQuery UI
    • More on jquery
  •   Tutorials
    • Microservices Tutorials
    • DotNet Core Tutorials
    • PostgreSql Tutorials

Linq in C Sharp (C#)

LINQ that stands for Language Integrated Query (pronounced as “link”) is a .NET language extension that supports data retrieval from different data sources like XML document, databases and collections. It was introduced in the .NET 3.5 framework. VB and C# are the languages that have LINQ capabilities.

Why Linq? If there is still ADO.Net!

One would think why LINQ was developed when ADO.NET was there for data retrieval. The main reason behind this was due to the concept “how the application saw relational data.” If we are working with a simple application that connects to a simple database, everything works well with ADO.NET. For example, a manufacturer’s ordering system in which there is a table for a customer and an order table that stores information regarding the order he makes.

However, if the database gets bigger with more tables i.e. the order table gets bigger with multiple tables for storing related data and also, when the application gets complex, we see an increasing amount of difference in the way application looks at the data. But still the programmer would want to work a single conceptual order without having to do a complex join operation for every order-related query. This is called the object-relational impedance mismatch.

For this reason, programmers implement their mapping layers to create a single entity like an object. For example, order object has methods for retrieval and update, which perform the database queries to get information.

Mapping layers, in short, conveniently isolate the application from the specifics of the logical database structures. In LINQ, there is a mapping between the data schemas in the object as well as the relational domain which makes it simpler to use.

Types of LINQ Objects in C#

We have different types of LINQ Objects available in C# and VB.NET.

  • LINQ To Objects
  • LINQ To DataSets
  • LINQ To SQL
  • LINQ to XML
  • LINQ To Entities
  • Write LINQ queries in C#

  • Use query syntax.
  • Use method syntax.
  • Use a combination of query syntax and method syntax.
  • Code: Use query syntax.

    The recommended way to write most queries is to use query syntax to create query expressions. 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
                                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];
    
    Code: Method syntax

    Some query operations must be expressed as a method call. The most common such methods are those that return singleton numeric values, such as Sum, Max, Min, Average, and so on. These methods must always be called last in any query because they represent only a single value and cannot serve as the source for an additional query operation. The following example shows a method call in a query expression:

                                List numbers1 = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
                                List numbers2 = new List() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
                                // Query #4.
                                double average = numbers1.Average();
    
                                // Query #5.
                                IEnumerable concatenationQuery = numbers1.Concat(numbers2);
                            
    Code: Mixed query and method syntax
                            // 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 numbersQuery =
                                from num in numbers1
                                where num < 3 || num > 7
                                select num;
    
                            int numCount2 = numbersQuery.Count();
                   
    Advantages of LINQ

  • We do not need to learn new query language syntaxes for different sources of data because it provides the standard query syntax for the various data sources.
  • In LINQ, we have to write the Less code in comparison to the traditional approach. With the use of LINQ, we can minimize the code.
  • LINQ provides the compile-time error checking as well as intelligence support in Visual Studio. This powerful feature helps us to avoid run-time errors.
  • LINQ provides a lot of built-in methods that we can be used to perform the different operations such as filtering, ordering, grouping, etc. which makes our work easy.
  • The query of LINQ can be reused.
  • Disadvantages of LINQ

  • With the use of LINQ, it's very difficult to write a complex query like SQL.
  • It was written in the code, and we cannot make use of the Cache Execution plan, which is the SQL feature as we do in the stored procedure.
  • If the query is not written correctly, then the performance will be degraded.
  • If we make some changes to our queries, then we need to recompile the application and need to redeploy the dll to the server.
  • Trending Post
    What is Anonymous methods in C#.
    Why Is It A Bad Idea To Throw Your Own Exceptions.
    How's The DLL Hell Problem Solved In .net?
    Interview Questions and Answers
    Describe the Async method of C#?
    Is it possible to serialise hashtables?
    Explain the differences between “out” and “ref” parameters in C#?
    How would you implement the Singleton design pattern in C#?
    What Are The Ways To Deploy An Assembly?
    What Are Advantages And Disadvantages Of Microsoft-provided Data Provider Classes In Ado.net?
    About us

    DotNet Palace is a community platform created and maintained by The articles are mainly focused on Microsoft stack technologies like C#, ASP.Net, MVC, .Net Core, SQL Server and Oracle, PostgreSQL, SQLite etc. To improve the site's content you can send your valuable suggestions at info.dotnetpalace@gmail.com

    Quick links
  • SOLID Principles
  • Questions
  • OOPS Principles
  • DotNet Palace Tutorials
  • Privacy Policy
  • Terms and Condition