使用LINQ在父对象列表中查找子对象

mat*_*atk 9 c# linq

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

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

public class Child
{
    public int ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在我希望Child对象具有特定的ID:

List<Parent> parents = GetParents();
Child childWithId17 = ???
Run Code Online (Sandbox Code Playgroud)

我怎么能用Linq做到这一点?

Ani*_*Ani 23

我想你想要:

Child childWithId17 = parents.SelectMany(parent => parent.Children)
                             .FirstOrDefault(child => child.ID == 17);
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*lex 6

您可以使用SelectMany:

Child childWithId17 = parents.SelectMany(p => p.Children)
                             .Where(ch=>ch.ID==17)
                             .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)