LINQ identity function?

Joe picture Joe · Sep 23, 2009 · Viewed 9.8k times · Source

Just a little niggle about LINQ syntax. I'm flattening an IEnumerable<IEnumerable<T>> with SelectMany(x => x).

My problem is with the lambda expression x => x. It looks a bit ugly. Is there some static 'identity function' object that I can use instead of x => x? Something like SelectMany(IdentityFunction)?

Answer

Dave Cousineau picture Dave Cousineau · Jun 5, 2012

Unless I misunderstand the question, the following seems to work fine for me in C# 4:

public static class Defines
{
   public static T Identity<T>(T pValue)
   {
      return pValue;
   }

   ...

You can then do the following in your example:

var result =
   enumerableOfEnumerables
   .SelectMany(Defines.Identity);

As well as use Defines.Identity anywhere you would use a lambda that looks like x => x.