LINQ let Clause

The let clause allows you to store a result of  an expression inside a query expression and use it on the remaining part of the  query. A let clause is useful when the query is  using an expression multiple times in a query or if you simply want to create a short alias to a very long variable or property name.

List<Person> persons = new List<Person>
    new Person { FirstName="John", LastName="Smith" },
    new Person { FirstName="Henry", LastName="Boon" },
    new Person { FirstName="Jacob", LastName="Lesley" }

var query = from p in persons
            let fullName = p.FirstName + " " + p.LastName
            select new { FullName = fullName };

foreach (var person in query)

Example 1

In the query expression in Example 1, the result of an expression to combine a  person’s FirstName and LastName properties and it store it to a variable for easy access. The  rest of the query expression after the let clause can now use the variable  containing the result of the expression. As you can see in the select clause of  the query expression in Example 1, we used the newly created variable from the  let clause and to create a property named FullName  during projection.

The let clause doesn’t have an equivalent query method. The following  rewrites the query expression above using the method syntax.

var query = persons.Select(p => new { fullName = p.FirstName + " " + p.LastName })
                   .Select(p => new { FullName = p.fullName });

The following are more examples of using the let  clause.

int[] numbers = { 1, 2, 3, 4, 5 };

//Query Expression
var query1 = from n in numbers
            let squared = n * n
            select squared;

//Method Syntax
var query2 = numbers.Select(n => new { squared = n * n })
                    .Select(n => n.squared);

Example 2

//Query Expression
var query1 = from p in persons
             let isTeenager = p.Age < 20 && p.Age > 12
             where isTeenager
             select new { p.FirstName, p.LastName };

//Method Syntax
var query2 = persons.Select(p => new { isTeenAger = p.Age < 20 && p.Age > 12 })
                    .Where(p => p.isTeenager)
                    .Select(p => new { p.FirstName, p.LastName });

Example 3

The above query uses the variable created by the let clause as an argument to  the where clause since the expression in the let clause is a boolean expression.