8

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

GurdeepS
  • 65,107
  • 109
  • 251
  • 387
  • You can use the following solution if your list contains loops: http://stackoverflow.com/questions/141467/recursive-list-flattening/24747394#answer-24747394 – Aidin Jul 14 '14 at 23:05

1 Answers1

20

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);
}
Jon
  • 428,835
  • 81
  • 738
  • 806