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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With