Let keyword introduces a new range variable in a LINQ query.This range variable stores the result of the sub expression.This variable can be used anywhere in the query ,after it is declared.
This helps keep many complex queries simple.
Using Let keyword in LINQ
Its used as:
sub expression1 let letVariable = query expression which returns a value sub expression2 which uses the letVariable
In the following example we have declared a generic list of Students.Every student can have one or many subjects.
List<Student> students = new List<Student> { new Student{Name="John",Subjects=new List<Subject>{ new Subject{Name="Maths",Marks=90 }, new Subject{Name="English",Marks=70 } } }, new Student{Name="Mark",Subjects=new List<Subject>{ new Subject{Name="Maths",Marks=66 }, new Subject{Name="English",Marks=55 } } }, new Student{Name="Amit",Subjects=new List<Subject>{ new Subject{Name="Maths",Marks=71 }, new Subject{Name="English",Marks=87 } } }, new Student{Name="Laxman",Subjects=new List<Subject>{ new Subject{Name="Maths",Marks=54 }, new Subject{Name="English",Marks=67 } } }, };
Now to find the list of all students who scored more than average score in Maths we will have to write complex linq query or use multiple queries.By using the Let clause we can use a single query as:
var result = from student in students let total = students.Select(x => x.Subjects.Where(y => y.Name == "Maths").Select(y => y.Marks).FirstOrDefault() ).Cast<int>().Sum() let average = total / students.Count() let markInMaths = (from subject in student.Subjects where subject.Name == "Maths" select subject.Marks).FirstOrDefault() where markInMaths > average select new { student.Name, markInMaths, average };
In the above query 2 LINQ let clauses are used markInMaths and average.These variables stores the marks in maths for a specific student and average of marks in Maths respectively.
We are using these 2 let variables in the where clause of the outermost query to filter the students
where markInMaths > average
the where clause will filter the list of students who have scored more than average in Maths.
Finally we can print the list of students:
foreach(var student in result) { Console.WriteLine("{0},{1},{2}", student.Name, student.markInMaths, student.average); }
The above statement will print the values for students John and Amit as they have above average marks in Maths.
Using Let keyword in LINQ helps manage complexity of Linq queries and allows to implement complex scenarios.
Leave a Reply