LINQ identity function?

后端 未结 7 2117
日久生厌
日久生厌 2020-12-03 16:22

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

My problem i

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 17:23

    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 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);
        }
    }
    

提交回复
热议问题