Wednesday, February 16, 2011

LINQ Tutorial : SelectMany extension method

Here's another thing I did not know about LINQ that I found out from this book.
SelectMany is how LINQ internally translates a collection of a collection into a flat collection.

Say you have a class:

public class Customer
      public Order[] Orders;

and you write the following LINQ:

var orders = from customer in Customers
             select customer.Orders;

Needless to say you get an IEnumerable<order[]>
However if you want an IEnumerable<order> you can do that in LINQ syntax simply as:

var orders = from customer in Customers
                  from order in customer.Orders
                       select order;

The compiler will actually translate it into a SelectMany call :
var orders = Customers.SelectMany(customer => customer.Orders);

In fact SelectMany will always be called when there is a from after the first from.