C# 7 tuples and lambdas

前端 未结 4 1229
[愿得一人]
[愿得一人] 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 03:01

    You should specify names of tuple properties (well, ValueTuple have fields) otherwise default names will be used, as you have seen:

    var list = new List<(int x, int y)>();
    

    Now tuple have nicely named fields which you can use

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

    Don't forget to add System.ValueTuple package from NuGet and keep in mind that ValueTuples are mutable structs.


    Update: Deconstruction currently represented only as an assignment to existing variables (deconstructon-assignment) or to newly created local variables (deconstruction-declaration). Applicable function member selection algorithm is the same as before:

    Each argument in argument list corresponds to a parameter in the function member declaration as described in §7.5.1.1, and any parameter to which no argument corresponds is an optional parameter.

    Tuple variable is a single argument. It cannot correspond to several parameters in the formal parameters list of the method.

提交回复
热议问题