【问题标题】:Find child objects in list of parent objects using LINQ使用 LINQ 在父对象列表中查找子对象
【发布时间】:2013-04-30 18:24:21
【问题描述】:

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

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

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

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

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

如何使用 Linq 做到这一点?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    我想你想要:

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

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

    【讨论】:

    • @Ani 对于空引用,您可以添加两个额外的 Where 条件。
    • @AkashKava:当然可以,但除非设计允许空值,否则无需添加它们。
    • 谢谢,接受这个答案,因为我喜欢 .FirstOrDefault 的简洁用法。
    • 我知道这是旧的,但我将如何根据子结果选择父项?因此,如果子列表满足条件,则获取父列表。
    【解决方案2】:

    您可以使用 SelectMany:

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

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多