SelectMany in Entity Framework

SelectMany in Entity Framework is an operator that flattens out the collection of collections into one single collection of objects. It is a very useful operator with many use cases.

Example Query

Consider the following query. The query returns list of Products under the ProductModel.

We can write the above query in Entity Framework as follows. The query returns the collection of ProductModel. Under each ProductModel we have collection of Products.

SelectMany

The selectMany helps flattens out the collection of collections into one single collection of objects. Now let use re write the above query using the selectMany

SelectMany flattens two collections. In the example below ProductModels is the first or outer collection. We need to choose the second or inner collection as the first argument to the SelectMany, which is Products (SelectMany(p => p.Products)

Next, we need to choose the shape of our output using a projection query. The lambda expression gets two arguments. The first argument is a reference to the outer collection (ProductModels). The second is a reference to the inner collection (Products).

The query returns a single collection, which is similar to what you get when you execute the SQL


Best Entity Framework Books
The Best Entity Freamework Books, which helps you to get started with Entity Framework  

SelectMany Multiple collections

You can chain of selectMany methods as shown in below. In our first selectMany projection, we have included ProductInventories collection. Now in the second selectMany we can flatten it again into a single collection.

References

SelectMany API

Summary

SelectMany converts collection of collections into one single collection of objects. You can also use it flatten the multiple hierarchical collections into a single collection.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top