Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I flatten a collection of objects (which in turn contain collections)?

Tags:

c#

linq

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

like image 582
GurdeepS Avatar asked Mar 26 '11 01:03

GurdeepS


1 Answers

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);
}
like image 115
Jon Avatar answered Sep 29 '22 00:09

Jon