Query Expression vs Dot Notation in LINQ (a concise talk)


Introduction

We can see there are two or more ways to achieve the same results in LINQ that is by using dot notation and query expression.

Look at the sample examples.

Query Expression Example

var results = from product in products
                orderby product.Price descending
                select new
                {
                    product.Name,
                    product.Price
                };
 
int count = 0;
// print out the names
foreach (var p in results)
{
    Console.WriteLine("Item: {0}, Cost: {1}", p.Name, p.Price);
    if (++count == 3)
    {
        break;
    }
}


Dot Notation Example

var results = products
                        .OrderByDescending(e => e.Price)
                        .Take(3)
                        .Select(e => new { e.Name, e.Price });
 
foreach (var p in results)
{
    Console.WriteLine("Item: {0}, Cost: {1}", p.Name, p.Price);
}


The idea is that there are two ways to express the same thing, but which way is the best?

The "dot" notation is usually called Lambda syntax. The first notation goes by a number of names but I usually call it the query syntax.

As I know, in general, the more seasoned (with LINQ) developers migrate towards the Lambda syntax but there are significant exceptions.

Lambda is more concise but performing multiple table joins is a nightmare. Joins are just much cleaner with the query syntax. The flip side is that there are a number of LINQ operations that only exist within the Lambda syntax: Single(), First(), Count() etc.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System