TechCognition

Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

LINQ Query Syntax and Method Syntax in C#

We generally write queries using Query syntax in LINQ (Language Integrated Query). There is another way called Method syntax to write queries in LINQ. In this article, we discuss what are the differences between query syntax and method syntax and also which is the best option while considering the performance.

Query Syntax: We can write the queries in LINQ using query syntax similar to SQL queries. For example, we can fetch the employee’s information whose name starts with "R" as below by using query syntax.

using System.Collections.Generic;

using System.Linq; 

namespace LinqExample

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] names = { "Mark", "Doug", "David", "Bob", "Raj", "Rasa" };

            IEnumerable<string> data = from n in names

                                        where n.StartsWith("R")

                                        select n; 

        }

    }

} 

It is easy to write LINQ queries using query syntax, but all LINQ queries used query syntax must be converted into method calls for the .NET runtime by the compiler. These method calls invoke the standard query operators such as Select, Where, Join, GroupBy, Max, Average, Having....etc

Method Syntax:  We can write LINQ queries using method syntax as shown below to fetch the employee’s information whose name starts with "R".

using System.Collections.Generic;

using System.Linq; 

namespace LinqExample

{

    class Program

    {

        static void Main(string[] args)

        {

            string[] names = { "Mark", "Doug", "David", "Bob", "Raj", "Rasa" };

            IEnumerable<string> data = names.Where(n => n.StartsWith("R"));

        }

    }

} 

It is somewhat difficult to write queries using method syntax as compared to query syntax. However, the code executes very fast if we write the queries using method syntax instead of query syntax because even query syntax queries also convert into method syntax by the compiler. So by writing the LINQ queries using method syntax, we can reduce the work for .NET compiler.

Add comment

Loading

© Copyright 2018 www.techcognition.com | Sitemap