Select Many Operator Part 1

Select Many Operator is part of the projection query operator supported by linq. SelectMany operator is mainly used for flattening out the hierarchy of collections into one single collection of objects. It merges each item into a single sequence that gets returned by the query results.

Here is the prototype for SelectMany operator

public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, IEnumerable<S>> selector);

 

The prototype takes IEnumerable of T and select delegate that returns IEnumerable of S.  The selectmany operator will merge each zero or more output returned from the select delegate into one output sequence.

The second prototype for selectmany operator looks like this.

public static IEnumerable<S> SelectMany<T, S>(
this IEnumerable<T> source,
Func<T, int, IEnumerable<S>> selector);

The second prototype is not much different from the first prototype, except it passes the zero based index of the element  to selector delegate.

Lets go through a simple example of how and where we can use selectmany operator.

image

image

We start off with an array of string which consists of complete name separated by space. In order to convert each name on its own, we make use of Selectmany operator passing the delegate an array of both names i.e the firstname and lastname by making use of split operator.  As you can see from the result we have all the names broken apart into one big list.

This same query could also have been written using the query syntax as follows.

image

 

The result of the above query is exactly the same, except the query syntax is much easier to follow and more readable.

Not only can you use selectmany operator in linq to objects but selectmany operator can also be used with linq to sql to flatten a particular hierarchy. Lets look through an example of that.

image

In this case I am using linq to sql ormapper to generate my classes. In the first part of the query, i filter the customers who belong to the city of London and then using the selectmany operator i merge all the orders for all the customers into one big list of sequence.

This same method syntax can be written using query syntax as follows.

image

Interesting point to mention at this stage is, although I am applying the filter for the city earlier in my query, if I were to apply the filter later down in the query, it still would not have been a bottle neck for performance because the entire query gets converted to sql which gets sent to the database. However if you were to be using linq to objects then it would be an appropriate decision to apply the filter earlier down in the query.

No Comments