HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

LINQ query that filters elements from a list of object

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqelementsqueryobjectthatfilterslistfrom

Problem

I have two lists of objects Person and PersonResult. Both are linked through the property PersonId. I need to create a filter for the list of PersonResult that meet certain criteria for the Person (e.g. Person.Gender == "female").

Im currently using the following LINQ query to achieve this:

PersonResultList = PersonResultList.Where(pr => 
    PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId) != null && 
    PersonList.FirstOrDefault(p => pr.PersonId == p.PersonId).Gender == "female");


This works apparently well, however, I must iterate twice through PersonList to check if the person exist and its gender. Is there a more elegant way to achieve this?

Solution

You can simply combine the conditions inside the FirstOrDefault() like

PersonResultList = PersonResultList
    .Where(pr => PersonList
                    .FirstOrDefault(p => pr.PersonId == p.PersonId 
                                         && p.Gender == "female") != null );


Because I only changed your existing code, it didn't came to my mind what Nikita Brizhak commented here .


You should probably use Any instead of FirstOrDefault

So let us change the code to

PersonResultList = PersonResultList
        .Where(pr => PersonList
                        .Any(p => pr.PersonId == p.PersonId 
                              && p.Gender == "female"));


This is based on the assumption that for each entry in the first list there will be only one entry in the second list.

Code Snippets

PersonResultList = PersonResultList
    .Where(pr => PersonList
                    .FirstOrDefault(p => pr.PersonId == p.PersonId 
                                         && p.Gender == "female") != null );
PersonResultList = PersonResultList
        .Where(pr => PersonList
                        .Any(p => pr.PersonId == p.PersonId 
                              && p.Gender == "female"));

Context

StackExchange Code Review Q#93973, answer score: 14

Revisions (0)

No revisions yet.