Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of SelectMany(x => x)?

Tags:

c#

lambda

I understand the use of lambda functions as a filter such as (x => x.Count() == 1), but what is the purpose of the (x => x)? When I take it out, the code doesn't compile, and every example of lambda functions I can find seems to use it to filter in one line instead of multiple lines without the lambda.

List<Tuple<int, int>> regVals = ReadRegValCollection.SelectMany(x => x).ToList();

The purpose of this gem is to flatten a List of Lists into a List

like image 261
SwimBikeRun Avatar asked Apr 18 '15 03:04

SwimBikeRun


1 Answers

x => x is a lambda expression that returns whatever argument it's provided with.

It's equivalent to a method declared as

public T Identity<T>(T item)
{
    return item;
}

It's commonly used with SelectMany method to flatten a collection declared as IEnumerable<IEnumerable<T>> into IEnumerable<T>.

SelectMany requires a delegate that matches Func<IEnumerable<TSource>, IEnumerable<TResult>>. In case when a source is IEnumerable<IEnumerable<T>> and you want a result to be IEnumerable<T> no projection has to be done on source collection elements, as they already are IEnumerable<TResult>.

like image 178
MarcinJuraszek Avatar answered Oct 13 '22 00:10

MarcinJuraszek