查找使用LINQ的父对象列表子对象 [英] Find child objects in list of parent objects using LINQ
本文介绍了查找使用LINQ的父对象列表子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于每个人都有的子对象的列表中的父对象的列表,我想找到的子对象匹配特定的ID。
Given a list of Parent objects that each have a list of Child objects, I want to find the child object matching a specific ID.
public class Parent
{
public int ID { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int ID { get; set; }
}
现在我想具有特定标识的子对象:
Now I want the Child object having a specific ID:
List<Parent> parents = GetParents();
Child childWithId17 = ???
我怎样才能做到这一点使用LINQ?
How can I do this using Linq?
推荐答案
我觉得你想要的:
Child childWithId17 = parents.SelectMany(parent => parent.Children)
.FirstOrDefault(child => child.ID == 17);
请注意,这里假设父母的儿童属性将不会是一个空引用或包含空子引用
Note that this assumes that Parent's Children property won't be a null-reference or contain null Child references.
这篇关于查找使用LINQ的父对象列表子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文