Ever run into the situation where you want to retrieve a
single collection of objects from a hierarchy like the one below?
IEnumerable<ClassA> {
ClassA{
IEnumerable<ClassB>
}
}
The first thing most people try is to use the LINQ Select () statement like so:
var classBCollection = classACollection.Select(a => a.ClassBCollection);
But when inspecting the type of classBCollection, we see it
has type IEnumerable<IEnumerable<ClassB>>
and NOT the desired type of simply IEnumerable<ClassB>. Luckily, LINQ provides another method called
SelectMany () which handles situations
like this perfectly. Simply changing our Select () from above to a SelectMany () gives us the correct IEnumerable<ClassB>
that we desired.
var classBCollection = classACollection.SelectMany(a => a.ClassBCollection);
Now we can deal with all of our ClassB objects in a single collection.