Thursday, July 26, 2012

SelectMany() in LINQ : What is it? and When to use it?

What MSDN says about SelectMany()

"Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence."

Let us understand the what SelectMany do by example. Let us consider we have two classes Book and Author as follows
 



Class Book contains the list of class Author. Make sense as Books has many authors.

Now let us consider a case when you want list of all authors (irrespective of books). How will you do this. If you use Select() as follows.



 
Select() returns the collection of collections (IEnumerable<IEnumerable<Author>>). Select Method just put all Author List one by one into other List.
To enumerate the list of authors you need two foreach loops as shown above.

SelectMany() Method as said on MSDN flattens the resulting sequences into one sequence as follows. SelectMany() method puts all Author List one by one into a single Author list.


 
When to Use the SelectMany

1. Consider a case when we want all authors from country India; Below is example how SelectMany is useful


Using SelectMany() we first converted all Author in one list and then applied condition over it. With Out SelectMany this would be very difficult.

2. We can use SelectMany()  over Select() when we want one single list. Consider more complex case where we have one more level of hierarchy. Like

League - > Teams - >  Players

In this case if we want the list of all players then we can use SelectMany .

2 comments:

Josh Jordan said...

SelectMany has been around since LINQ was introduced - it is not new in .NET 4.

Sanket Kulkarni said...

Thanks Josh for comment. I will correct it.