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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With