The LET clause allows us 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 we simply want to create an short alias to a very long variable or property name.
For Example:
We will create a Person class which will contain two properties as FirstName and LastName,so our Person class will look like as:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Not in any event write:
List<Person> obj_persons = new List<Person>
{
new Person { FirstName="Rajesh",LastName="Sathua" },
new Person { FirstName="Vinod",LastName="Shinde" },
new Person { FirstName="Preeti",LastName="Patle" },
new Person { FirstName="Rutu",LastName="Dixit" }
};
var query = from obj in obj_persons
let fullName = obj.FirstName + string.Empty + obj.LastName
select new { FullName = fullName };
foreach (var person in query)
{
Response.Write(person.FullName + "<br/>");
}
Output:
Rajesh Sathua
Vinod Shinde
Preeti Patle
Rutu Dixit Now we can again simplify above query as:
query = obj_persons.Select(p => new { fullName = p.FirstName + string.Empty + p.LastName })
.Select(p => new { FullName = p.fullName });
foreach (var person in query)
{
Response.Write(person.FullName + "<br/>");
}
Output would be the same as above.