Different Ways to Write LINQ Queries in C#

Different Ways to Write LINQ Queries in C# with Examples

In this article, I will discuss the Different Ways to write LINQ Queries, i.e., LINQ Query Syntax and Method Syntax with Examples using C#. Please read our previous article discussing the Architecture of LINQ, i.e., how LINQ works.

What are the different things required to write a LINQ Query?

To write a LINQ query, we need the following three things

  1. Data Source (In-Memory Objects, SQL Server, XML Document, etc)
  2. Query
  3. Execution of the Query
What is a Query?

A query is nothing but a set of instructions applied to a data source (i.e., In-Memory Objects, SQL Server, XML Document, 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. This also means what will return from that query, whether it will return a particular value, 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?

In C#, LINQ (Language-Integrated Query) queries can be written in two primary ways: Query Syntax and Method Syntax. Both can be used to perform the same operations. Still, they have different styles, and some developers may prefer one over the other based on the readability and complexity of the 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 totally depends on your personal preference. But the point that you need to keep in mind is, behind the scenes, the LINQ queries written using query syntax are translated into their lambda expressions before they are compiled. 

LINQ Query Syntax:

Query Syntax is more similar to SQL, providing a readable and declarative way of writing queries. Under the hood, it gets translated into Method Syntax at compile time. This is one of the easy ways to write complex LINQ queries in an easy and readable format. If you are familiar with SQL Queries, it will be easy for you to write LINQ queries using this query syntax. The syntax is given below.

LINQ Query Syntax

Characteristics:
  • Resembles SQL-like declarative style.
  • It can be more readable, especially for those familiar with SQL.
  • Not all operations can be expressed in Query Syntax; some require a switch to Method Syntax.
LINQ Method Syntax:

Method Syntax (also known as Fluent Syntax or Lambda Syntax) uses extension methods included in the System.Linq namespace and can be chained together to perform complex queries. It is similar to calling methods in a traditional object-oriented programming language. Method syntax has become most popular nowadays for writing LINQ queries. In this approach, the LINQ query is written using multiple methods by combining them with a dot (.), i.e., method chaining. The Syntax is given below:

LINQ Method Syntax

Characteristics:
  • Utilizes lambda expressions.
  • It can be more concise for complex queries.
  • Offers slightly more methods and flexibility than Query Syntax.
  • It can be easier to understand for those familiar with lambda expressions and functional programming.
LINQ Mixed Syntax:

You can also mix both syntaxes, although this is less common. This is the combination of both Query and Method syntax. The syntax is given below.

LINQ Mixed Syntax

Comparison Between Method and Query Syntax:
  • Interchangeability: Most queries can be written in either syntax, and it often comes down to personal or team preference.
  • Performance: There is no performance difference between the two, as Query Syntax is translated into Method Syntax at compile time.
  • Complexity: For more complex queries, Method Syntax can be more powerful and flexible, but Query Syntax can be more intuitive for simpler queries or for those with a background in SQL.

Let us understand how to use Query Syntax, Method Syntax, and Mixed Syntax with examples. We have an integer list, and we need to write a LINQ query to return all the integers greater than 5. We are going to create a console application.

Example Using LINQ Query Syntax in C#:

The following Example code is self-explained, so please go through the comment lines. Here, we have created a collection of integers, i.e., going to be our data source. Then, we created one LINQ query, which will fetch the numbers from the data source that are greater than 5, and finally, we executed the query and printed the result on the Console window. The LINQ query contains three things, i.e., Data Source, Condition, and Selection.

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

            //Step2: Query
            //LINQ Query using Query Syntax to fetch all numbers which are > 5
            var QuerySyntax = from obj in integerList //Data Source
                              where obj > 5 //Condition
                              select obj; //Selection

            //Step3: 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 LINQ Method Syntax in C#:

Let us rewrite the previous example using the LINQ Method Syntax. The following Example code is self-explained, so please go through the comment lines.

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

            //Step2: Query
            //LINQ Query using Query Syntax to fetch all numbers which are > 5
            var QuerySyntax = integerList.Where(obj => obj > 5).ToList(); 

            //Step3: Execution
            foreach (var item in QuerySyntax)
            {
                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 LINQ Mixed Syntax in C#:

Let us change our requirements. 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

When should you use the LINQ Method and Query Syntax?

In the .NET framework, LINQ (Language Integrated Query) provides two main ways to write queries: Method syntax and Query syntax. Both syntaxes can be used to perform a wide range of operations, such as filtering, sorting, and grouping, but there are some differences in how they are used and in their capabilities.

When should you use LINQ Method Syntax (Fluent Syntax)?
  • For more complex queries, especially those involving multiple operations. Method syntax can be more concise and easier to read for these types of queries.
  • When you need to use lambda expressions for more control or complexity in the query.
  • If you are comfortable with functional programming concepts since it’s similar to functional programming methods in other languages.
  • When the operations you need are not supported by query syntax (e.g., Zip, Aggregate).
When should you use LINQ Query Syntax (Comprehension Syntax)?
  • For simpler queries. Query syntax can be more readable and resemble SQL, making it easier for those familiar with SQL to understand.
  • When you prefer a declarative programming style.
  • If the query closely aligns with SQL syntax (e.g., selecting from a single collection).

In the next article, I will discuss IEnumerable and IQuerable in LINQ with Examples. I hope you enjoy this article and understand the Linq Query Syntax and Linq Method Syntax with Examples.

1 thought on “Different Ways to Write LINQ Queries in C#”

Leave a Reply

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