let keyword
The 'let' keyword is useful in query syntax. It projects a new range variable, allows re-use of the expression and makes the query more readable.
For example, you can compare string values and select the lowercase string value as shown below:
Example: let in LINQ query - C#
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 }
};
var lowercaseStudentNames = from s in studentList
where s.StudentName.ToLower().StartsWith("r")
select s.StudentName.ToLower();
As you can see, the ToLower() method is used multiple times in the above query. The following example use 'let' to introduce new variable 'lowercaseStudentName' that will be then used in every where. Thus, let keyword to make the query more readable.
Example: let keyword in C#
var lowercaseStudentNames = from s in studentList
let lowercaseStudentName = s.StudentName.ToLower()
where lowercaseStudentName.StartsWith("r")
select lowercaseStudentName;
foreach (var name in lowercaseStudentNames)
Console.WriteLine(name);
Example: let keyword in VB.Net
Dim lowercaseStudentNames = From s In studentList
Let lowercaseStudentName = s.StudentName.ToLower()
Where lowercaseStudentName.StartsWith("r")
Select lowercaseStudentName;
Output:
ram
ron