Skip to content

SelectWhere method #49

@JeevanJames

Description

@JeevanJames

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.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions