Search code examples
c#pythonc#-7.0valuetuple

Creating subtuple from a valuetuple


Is there a functionality for C# 7 ValueTuple similar to Python's slicing? The syntax for value tuples in C# is similar to Python but I can't find an elegant way to get subtuple from tuple for example.

In Python 3:

 tuple = (1,2,3)
 subtuple = t[:2]   #subtuple is (1, 2)

In C# 7:

 var tuple = (1,2,3)   //Very similar to Python!
 var subtuple = (tuple.Item1, tuple.Item2)  //Not very elegant, especially for bigger tuples

Solution

  • No, there is nothing like that in C#. Due to the statically-typed nature of C#, a feature like that couldn't work with arbitrary expressions for the slice points.

    I think that the closest you can get is to create a bunch of extension methods that have the slice points embedded in their names. E.g.:

    public static (T1, T2) Take2<T1, T2, T3>(this (T1, T2, T3) tuple) =>
        (tuple.Item1, tuple.Item2);
    
    var tuple = (1,2,3);
    var subtuple = tuple.Take2();
    

    Note that if the tuple members have names, this will strip them off.