Sometimes we need to perform a heavy operation in the Where clause to satisfy the predicate and then do the same operation in the Select clause to return the final projection.
For example:
var results = students
.Where(s => CalculateGrade(s.Marks) == 'A')
.Select(s => new { Name = s.Name, Grade = CalculateGrade(s.Marks) });
This is possible with the let keyword when using LINQ syntax:
var results = from s in students
let grade = CalculateGrade(s.Marks)
where grade == 'A'
select new { Name = s.Name, Grade = grade };
But with method syntax, it is difficult and we typically end up running the operation multiple times. Once recommendation is to create a projection with the initial object and calculated object and work with that:
var results = students
.Select(s => new { Student = s, Grade = CalculateGrade(s.Marks) })
.Where(s => s.Grade == 'A')
.Select(new { Name = s.Student.Name, Grade = s.Grade });
The SelectWhere method enables this scenario without needing the projection.
Sometimes we need to perform a heavy operation in the
Whereclause to satisfy the predicate and then do the same operation in theSelectclause to return the final projection.For example:
This is possible with the
letkeyword when using LINQ syntax:But with method syntax, it is difficult and we typically end up running the operation multiple times. Once recommendation is to create a projection with the initial object and calculated object and work with that:
The
SelectWheremethod enables this scenario without needing the projection.