Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ在父对象列表中查找子对象_C#_Linq - Fatal编程技术网

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

C# 使用LINQ在父对象列表中查找子对象,c#,linq,C#,Linq,给定一个父对象列表,每个父对象都有一个子对象列表,我希望找到与特定ID匹配的子对象 public class Parent { public int ID { get; set; } public List<Child> Children { get; set; } } public class Child { public int ID { get; set; } } 公共类父类 { 公共int ID{get;set;} 公共列表子项{get;set;}

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

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

public class Child
{
    public int ID { get; set; }
}
公共类父类
{
公共int ID{get;set;}
公共列表子项{get;set;}
}
公营儿童
{
公共int ID{get;set;}
}
现在,我希望子对象具有特定ID:

List<Parent> parents = GetParents();
Child childWithId17 = ???
List parents=GetParents();
ID为17的儿童=???
如何使用Linq实现这一点?

我想您需要:

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

请注意,这假定父级的Children属性不是空引用或包含空子引用。

您可以使用SelectMany:

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

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