Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

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.

Posted on Monday, November 18, 2013 6:33 PM .net , linq | Back to top


Comments on this post: Flattening Collection Hierarchies with LINQ

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net