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

I have an IEnumerable collection, which is hierarchical since one element contains several inside it. That way, if I am doing the count, I can get 7-8 as the return int when there really can be 500 elements (since they are nested).

How can I smooth this collection into a collection with all the elements and without nesting?

thank

+5
source share
1 answer

Assuming that it smallEnumerableis a collection with 7-8 elements, each of which has a property SubItemsthat is itself enumerable for elements of the same type, then you smooth out the following:

var flattened = smallEnumerable.SelectMany(s => s.SubItems);

SubItems SubItems , :

IEnumerable<MyType> RecursiveFlatten(IEnumerable<MyType> collection)
{
    return collection.SelectMany(
      s => s.SubItems.Any() ? s.Concat(RecursiveFlatten(s.SubItems)) : s);
}
+13

All Articles