23

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.

Will Strohl
  • 1,646
  • 2
  • 15
  • 32
  • 6
    Voting the question down was pretty harsh. I searched SO *and* Google both before typing out this abstract answer. If the tools here were better, maybe I wouldn't have a duplicate question. – Will Strohl Mar 25 '15 at 01:44
  • 7
    Upvoted. This was the top result for my google search "linq select parent objects based on child objects". If I had the rep, I would unmark this as a duplicate; the linked question provides a similar answer, but the way the question title is phrased is not intuitively similar. – Will Feb 04 '16 at 23:57
  • 8
    Many people on SO are way too quick to perform actions, without thinking them through. It's quite annoying and sometimes downright upsetting. – Will Strohl Feb 05 '16 at 16:54

1 Answers1

44

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));
Erik
  • 5,355
  • 25
  • 39