C#中的元组和解包分配支持?

时间:2011-12-15 03:37:36

标签: c# tuples iterable-unpacking decomposition

在Python中我可以写

def myMethod():
    #some work to find the row and col
    return (row, col)

row, col = myMethod()
mylist[row][col] # do work on this element

但在C#中,我发现自己写出了

int[] MyMethod()
{
    // some work to find row and col
    return new int[] { row, col }
}

int[] coords = MyMethod();
mylist[coords[0]][coords[1]] //do work on this element

Pythonic的方式显然更加清洁。有没有办法在C#中做到这一点?

5 个答案:

答案 0 :(得分:29)

从C#7开始,您可以安装System.ValueTuple

PM> Install-Package System.ValueTuple

然后您可以打包并解压缩ValueTuple

(int, int) MyMethod()
{
    return (row, col);
}

(int row, int col) = MyMethod();
// mylist[row][col]

答案 1 :(得分:15)

.NET中有一组Tuple类:

Tuple<int, int> MyMethod()
{
    // some work to find row and col
    return Tuple.Create(row, col);
}

但是没有像在Python中那样解压缩它们的紧凑语法:

Tuple<int, int> coords = MyMethod();
mylist[coords.Item1][coords.Item2] //do work on this element

答案 2 :(得分:7)

扩展可能会让它更接近Python元组解包,效率更高但更易读(和Pythonic):

public class Extensions
{
  public static void UnpackTo<T1, T2>(this Tuple<T1, T2> t, out T1 v1, out T2 v2)
  {
    v1 = t.Item1;
    v2 = t.Item2;
  }
}

Tuple<int, int> MyMethod() 
{
   // some work to find row and col
   return Tuple.Create(row, col);
}

int row, col;    
MyMethod().UnpackTo(out row, out col);
mylist[row][col]; // do work on this element

答案 3 :(得分:1)

C#是一种强类型语言,其类型系统强制执行一项规则,即函数可以包含无(void)或1返回值。 C#4.0引入了Tuple类:

Tuple<int, int> MyMethod()
{
    return Tuple.Create(0, 1);
}

// Usage:
var myTuple = MyMethod();
var row = myTuple.Item1;  // value of 0
var col = myTuple.Item2;  // value of 1

答案 4 :(得分:1)

这是一个带有值解包的zip示例。这里zip返回元组上的迭代器。

int[] numbers = {1, 2, 3, 4};
string[] words = {"one", "two", "three"};

foreach ((var n, var w) in numbers.Zip(words, Tuple.Create))
{
    Console.WriteLine("{0} -> {1}", n, w);
}

输出:

1 -> one
2 -> two
3 -> three