How can I flatten a collection of objects (which in turn contain collections)?
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?
Thanks
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);
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);
}
精彩评论