23

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#でこれを行う方法はありますか?

4

5 に答える 5

49

.NET 4.7 以降では、以下をパックおよびアンパックできますValueTuple

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

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

.NET 4.6.2 以前の場合、System.ValueTupleをインストールする必要があります。

PM> Install-Package System.ValueTuple
于 2017-08-10T15:23:04.390 に答える
19

.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
于 2011-12-15T03:42:03.350 に答える
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
于 2014-04-11T09:14:53.070 に答える
2

voidC#は、関数がなし( )または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
于 2011-12-15T03:44:49.683 に答える
2

値のアンパックを含む 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
于 2018-04-05T15:29:16.203 に答える