Different Ways to write LINQ Query

Different Ways to Write LINQ Query with Examples

In this article, I am going to discuss the Different Ways to write LINQ Query with examples. Please read our previous article where we discussed the Architecture of LINQ i.e. how LINQ works. In this article, we are going to discuss the following pointers.

  1. Different things required to write a LINQ Query?
  2. What is a Query?
  3. What are the different ways to write a LINQ query?
  4. Example of using both Method and Query Syntax.
What are the different things required to write a LINQ Query?

In order to write a LINQ query, we need the following three things

  1. Data Source (in-memory objects, SQL, XML)
  2. Query
  3. Execution of the query
What is a Query?

A query is nothing but a set of instructions which is applied on a data source (i.e. in-memory objects, SQL, XML, etc.) to perform certain operations (i.e. CRUD operations) and then tells the shape of the output from that query. That means the query is not responsible for what will be the output rather it is responsible for the shape of the output. Means what is going to return from that query whether it is going to return a particular value, or a particular list or an object.

Each query is a combination of three things. They are as follows:

  1. Initialization (to work with a particular data source)
  2. Condition (where, filter, sorting condition)
  3. Selection (single selection, group selection or joining)
What are the different ways to write a LINQ query?

We can write the LINQ query in three different ways. They are as follows

  1. Query Syntax
  2. Method Syntax
  3. Mixed Syntax (Query + Method)

Note: From the performance point of view there is no difference between the above three approaches. So, which you need to use, it totally depends on your personal preference. But the point that you need to keep in mind is, behind the scene, the LINQ queries written using query syntax are translated into their lambda expressions before they are compiled. 

LINQ Query Syntax:

This is one of the easy ways to write complex LINQ queries in an easy and readable format. The syntax for this type of query is very much similar to SQL Query. If you are familiar with SQL queries then it is going to be easy for you to write LINQ queries using this query syntax. The syntax is given below.

LINQ Query Syntax

LINQ Method Syntax:

Method syntax becomes most popular now a day to write LINQ queries. It uses a lambda expression to define the condition for the query. Method syntaxes are easy to write simple queries to perform read-write operations on a particular data source. But for complex queries Method syntaxes are a little hard to write as compared to query syntax.

In this approach, the LINQ query is written by using multiple methods by combining them with a dot (.). The Syntax is given below:

LINQ Method Syntax

LINQ Mixed Syntax:

This is the combination of both Query and Method syntax. The syntax is given below.

LINQ Mixed Syntax

 

 

 

 

Let us understand how to use Query Syntax, Method Syntax, and Mixed Syntax with examples.

Example: We have an integer list and we need to write a LINQ query which will return all the integers which are greater than 5. We are going to create a console application.

Example Using Query Syntax:
using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Data Source
            List<int> integerList = new List<int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            //LINQ Query using Query Syntax
            var QuerySyntax = from obj in integerList
                              where obj > 5
                              select obj;

            //Execution
            foreach(var item in QuerySyntax)
            {
                Console.Write(item + " ");
            }

            Console.ReadKey();
        }
    }
}

Now run the application and it will display the values 6 7 8 9 10 as expected in the console window. Let us understand what we did in the above code.

Linq Query Syntax Example

Example Using Method Syntax:

Let us rewrite the same example using LINQ Method Syntax.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Data Source
            List<int> integerList = new List<int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            //LINQ Query using Method Syntax
            var MethodSyntax = integerList.Where(obj => obj > 5).ToList();

            //Execution
            foreach(var item in MethodSyntax)
            {
                Console.Write(item + " ");
            }
            
            Console.ReadKey();
        }
    }
}

Now run the application and you will get the output as expected. Let us have a look at the following diagram to understand Method Syntax.

LINQ Method Syntax Example

Example Using Mixed Syntax:

Let us change our requirement. First, we need to filter the list where the value is greater than 5 and then we need to calculate the sum.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Data Source
            List<int> integerList = new List<int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            //LINQ Query using Mixed Syntax
            var MethodSyntax = (from obj in integerList
                                where obj > 5
                                select obj).Sum();

            //Execution
            Console.Write("Sum Is : " + MethodSyntax);
            
            Console.ReadKey();
        }
    }
}

Now run the application and you will see the output as expected. Let us understand what we did in the above code by looking at the following image.

LINQ Mixed Syntax Example

In the next article, I am going to discuss IEnumerable and IQuerable in LINQ with examples. I hope this article gives you a basic understanding of Different Ways to write LINQ Query.

Leave a Reply

Your email address will not be published. Required fields are marked *