Linq选择子对象具有匹配子对象的父对象 [英] Linq to Select Parent Objects Where Child Objects Have a Matching Child Object

查看:36
本文介绍了Linq选择子对象具有匹配子对象的父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

这是直接的Linq-to-Objects:

This is straightfoward Linq-to-Objects:

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

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

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));

这篇关于Linq选择子对象具有匹配子对象的父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆