Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SelectWhere method #49

Open
JeevanJames opened this issue Feb 23, 2022 · 0 comments
Open

SelectWhere method #49

JeevanJames opened this issue Feb 23, 2022 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@JeevanJames
Copy link
Owner

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.

@JeevanJames JeevanJames added the enhancement New feature or request label Feb 23, 2022
@JeevanJames JeevanJames self-assigned this Feb 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant