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. As part of this article, we will 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?

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 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 similar to SQL and is often more readable, especially for those familiar with SQL. It is declarative and describes what you want to achieve. 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

LINQ Method Syntax:

Method Syntax uses extension methods and lambda expressions. It can be more concise and is often more flexible for composing complex queries. Method syntax has become most popular nowadays for writing 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 harder to write than query syntax. In this approach, the LINQ query is written by using multiple methods by combining them with a dot (.), i.e., Method Chaining. The Syntax is given below:

LINQ Method Syntax

LINQ Mixed Syntax:

You can also mix both syntaxes, although this is less common. A combination of query and method syntax can be the most readable solution in some cases, particularly for more complex queries. 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. We have an integer list and need to write a LINQ query that will 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 same 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

Choosing Between Method and Query Syntaxes in C#:

Use LINQ Query Syntax:

Query Syntax is often more readable for queries that involve joining, grouping, or sorting operations. It is closer to the SQL style of queries and is great for developers already comfortable with SQL. The LINQ Query Syntax in C# is often preferred in certain scenarios due to its readability and similarity to SQL. It’s particularly advantageous in the following situations:

  • SQL-Like Queries: For developers familiar with SQL, Query Syntax provides a more intuitive and familiar way to compose queries. Its declarative nature makes it easy to read and understand, especially for simple queries.
  • Complex Queries: When dealing with complex queries that involve multiple operations like joins, grouping, and ordering, Query Syntax can be more readable and organized. The operations flow logically, similar to how SQL queries are structured.
  • Comprehension Syntax: For those who prefer the comprehension syntax (from…where…select), which is more expressive and closer to natural language.
  • Grouping Operations: When performing grouping operations, Query Syntax often results in more concise and readable code compared to Method Syntax.
  • Joining Operations: Query Syntax can be more straightforward and less verbose for queries involving multiple joins, especially those that resemble relational database queries.
  • Readability and Maintainability: When the priority is to have code that is easy to read and maintain. Query Syntax often leads to cleaner filtering, sorting, and selection logic separation.
Use LINQ Method Syntax:

Method Syntax Provides more methods and is generally more powerful for complex queries. It’s a good choice for developers with a more functional programming approach. LINQ Method Syntax in C# is often preferred in several scenarios due to its flexibility, powerful chaining capability, and alignment with functional programming paradigms. Here are some situations where Method Syntax is particularly advantageous:

  • Complex Filtering and Transformations: Method Syntax is well-suited for queries that involve complex conditions or transformations. Lambda expressions in Method Syntax can be more expressive and concise for these scenarios.
  • Chaining Multiple Operations: Method Syntax allows easy chaining of multiple LINQ operations. This can be particularly useful when building up queries dynamically or applying multiple transformations and filters.
  • Availability of More Methods: Not all LINQ operations are available in Query Syntax. Method Syntax provides access to a broader range of methods (like Aggregate, Sum, Max, Min, Average, FirstOrDefault, etc.), which might be necessary for certain operations.
  • Consistency with Fluent APIs: Method Syntax aligns well with fluent APIs and functional programming styles in C#. Method Syntax can be a more consistent choice if you work in a codebase that heavily uses these paradigms.
  • Mixed Operations: In some cases, you might need to mix LINQ with non-LINQ operations or use methods that don’t have direct equivalents in Query Syntax. Method Syntax is more flexible in integrating these kinds of operations.
  • Readability for Short Queries: Method Syntax can be more readable and concise than Query Syntax for shorter or simpler queries.

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 *