Linq选择父对象,其中子对象具有匹配的子对象

我将如何编写一个LINQ语句来选择在其集合中具有匹配子对象的父对象? 这是示例类。

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

在上面的示例中,我想返回包含具有特定昵称的子项的所有父项。

这是直截了当的Linq-to-Objects:

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

对于Linq-to-Entities,如果未将子对象作为实体进行跟踪,则可能需要在子对象标识符字段上进行匹配:

 int childObjectIdToMatch = childObjectToMatch.ID; dbContext.Parents.Where(p => p.Children.Any(c => c.ID == childObjectIdToMatch));