C# 使用LINQ在父对象列表中查找子对象
给定一个父对象列表,每个父对象都有一个子对象列表,我希望找到与特定ID匹配的子对象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;}
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的简洁用法。我知道这很旧,但如何根据子结果选择父项?因此,如果父列表的子列表满足条件,则获取父列表。