C# 7 tuples and lambdas

前端 未结 4 1238
[愿得一人]
[愿得一人] 2020-12-15 02:36

With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

var list         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 02:43

    The program you're running into is the inability of the compiler to infer the type in this expression:

    list.Select(((int x, int y) t) => t.x * 2 + t.y / 2);
    

    But since (int, int) and (int x, int y) are the same CLR type (System.ValueType), if you specify the type parameters:

    list.Select<(int x, int y), int>(t => t.x * 2 + t.y / 2);
    

    It will work.

提交回复
热议问题