如何展平对象的集合(而对象又包含集合)? [英] How can I flatten a collection of objects (which in turn contain collections)?
问题描述
我有一个IEnumerable集合,该集合是分层的,其中一个元素包含多个元素.因此,如果我做一个计数,当实际上可能有500个项目(因为它们是嵌套的)时,我可能会得到7-8作为返回值int.
I have an IEnumerable collection, which is hierarchical in that one element contains several within it. Thus, if I do a count, I may get 7-8 as the return int, when really there could be 500 items (as they're nested).
如何将这个集合扁平化为一个包含所有元素且没有嵌套的集合?
How can I flatten this collection into a collection with all the elements and no nesting?
谢谢
推荐答案
假定smallEnumerable
是具有7-8个项目的集合,每个项目都有一个属性SubItems
,该属性本身是该项目的可枚举相同的类型,则您需要像这样扁平化:
Assuming that smallEnumerable
is the collection with 7-8 items, each one of which has a property SubItems
which is itself an enumerable of items of the same type, then you flatten like this:
var flattened = smallEnumerable.SelectMany(s => s.SubItems);
如果每个SubItems
本身都可以具有SubItems
,则按顺序进行一些递归:
If each one of the SubItems
can have SubItems
itself, then some recursion is in order:
IEnumerable<MyType> RecursiveFlatten(IEnumerable<MyType> collection)
{
return collection.SelectMany(
s => s.SubItems.Any() ? s.Concat(RecursiveFlatten(s.SubItems)) : s);
}
这篇关于如何展平对象的集合(而对象又包含集合)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!