我有一个分层的对象结构:
Parent
List(of Child)
Child
List (of SubChild)
是否可以使用LINQ(最好使用Lambda)从Parent(作为新列表)获取每个SubChild?
传统上,它将在循环内完成:
Foreach(Child in Parent)
.. Foreach(SubChild in Child)
.... Add SubChild to FullSubChildList
最佳答案
使用Enumerable.SelectMany
投影和展平层次结构:
var FullSubChildList =
Parent.SelectMany(p => p.ChildList).SelectMany(c => c.SubChildList).ToList();
如果Parent是
IEnumerable<Child>
而Child是IEnumerable<SubChild>
(根据您的代码示例):var FullSubChildList = Parent.SelectMany(p => p).SelectMany(c => c).ToList();
关于c# - LINQ可以返回嵌套的对象集吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24695964/