Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Select Parent Objects Where Child Objects Have a Matching Child Object [duplicate]

Tags:

How would I go about writing a LINQ statement that selects the parent objects that have a matching child object in it's collection? Here's example classes.

class Parent {
    int ID { get; set; }
    string Name { get; set; }
    List<Child> Children { get; set; }
}

class Child {
    int ID { get; set; }
    string Name { get; set; }
    string Nickname { get; set; }
}

In the example above, I would like to return all of the parents that contain a child with a specific nickname.

like image 433
Will Strohl Avatar asked Mar 24 '15 21:03

Will Strohl


1 Answers

This is straightfoward Linq-to-Objects:

listOfParents.Where(p => p.Children.Contains(childObjectToMatch))

For Linq-to-Entities, if the child object isn't tracked as an entity you might need to match on the child object identifier field:

int childObjectIdToMatch = childObjectToMatch.ID;
dbContext.Parents.Where(p => p.Children.Any(c => c.ID == childObjectIdToMatch));
like image 60
Erik Avatar answered Oct 02 '22 16:10

Erik