我如何编写LINQ语句来选择在其对象中具有匹配子对象的父对象?这是一个示例类。
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; }
}
在上面的示例中,我想返回包含具有特定昵称的孩子的所有父母。
答案 0 :(得分:32)
这是直截了当的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));