LINQ identity function?

2019-01-12 01:34发布

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)?

7条回答
相关推荐>>
2楼-- · 2019-01-12 02:30

With C# 6.0 things are getting better. We can define the Identity function in the way suggested by @Sahuagin:

static class Functions
{
    public static T It<T>(T item) => item;
}

and then use it in SelectMany the using static constructor:

using Functions;

...

var result = enumerableOfEnumerables.SelectMany(It);

I think it looks very laconic in the such way. I also find Identity function useful when building dictionaries:

class P
{
    P(int id, string name) // sad, we are not getting Primary Constructors in C# 6.0
    {
        ID = id;
        Name = id;
    }

    int ID { get; }
    int Name { get; }

    static void Main(string[] args)
    {
        var items = new[] { new P(1, "Jack"), new P(2, "Jill"), new P(3, "Peter") };
        var dict = items.ToDictionary(x => x.ID, It);
    }
}
查看更多
登录 后发表回答