11

给定一个父对象列表,每个对象都有一个子对象列表,我想找到与特定 ID 匹配的子对象。

public class Parent
{
    public int ID { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public int ID { get; set; }
}

现在我想要具有特定 ID 的子对象:

List<Parent> parents = GetParents();
Child childWithId17 = ???

如何使用 Linq 做到这一点?

4

2 回答 2

26

我想你想要:

Child childWithId17 = parents.SelectMany(parent => parent.Children)
                             .FirstOrDefault(child => child.ID == 17);

请注意,这假定 Parent 的 Children 属性不会是 null 引用或包含 null Child 引用。

于 2013-04-30T10:23:29.670 回答
7

您可以使用 SelectMany:

Child childWithId17 = parents.SelectMany(p => p.Children)
                             .Where(ch=>ch.ID==17)
                             .FirstOrDefault();
于 2013-04-30T10:24:21.757 回答