2013-04-30 102 views
6

给定一个父对象列表,每个父对象都有一个子对象列表,我想查找与特定ID匹配的子对象。使用LINQ在父对象列表中查找子对象

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?

回答

17

我想你想:

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

注意,这个假设父母的儿童属性将不会是一个空引用或包含空儿童引用。

+0

+1,安仁:)这是非常有用! – zey 2013-04-30 10:26:18

+0

@Ani为null引用可以将两个额外的Where条件加起来。 – 2013-04-30 10:27:55

+0

@AkashKava:当然,但除非设计允许空值,否则无需添加它们。 – Ani 2013-04-30 10:29:50

6

可以使用的SelectMany:

Child childWithId17 = parents.SelectMany(p => p.Children) 
          .Where(ch=>ch.ID==17) 
          .FirstOrDefault();