【问题标题】:How to turn a Tuple into an Array in C#?如何在 C# 中将元组转换为数组?
【发布时间】:2016-09-05 18:12:31
【问题描述】:

我找不到任何关于此的信息,所以我不确定它是否可能,但 我有一个包含二维数组中元素坐标的元组。我希望能够找到二维数组中元素之间的距离并且要做到这一点,我想要一维数组形式中元素的位置(我不确定更好的方法去做这个)。那么是否有可能将元组变成数组?

这是数组:

string[,] keypad = new string[4, 3]
        {
            {"1", "2", "3"},
            {"4", "5", "6"},
            {"7", "8", "9"},
            {".", "0", " "}
        };

这是我用来获取多维数组中元素坐标的方法:

public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)
    {
        int w = matrix.GetLength(0); // width
        int h = matrix.GetLength(1); // height

        for (int x = 0; x < w; ++x)
        {
            for (int y = 0; y < h; ++y)
            {
                if (matrix[x, y].Equals(value))
                    return Tuple.Create(x, y);
            }
        }

        return Tuple.Create(-1, -1);
    }

【问题讨论】:

  • C# Convert Tuple into multi-dimensional arraystackoverflow.com/questions/13982940/…上进行谷歌搜索
  • @MethodMan 我想把一个元组变成一个数组而不是一个多维数组
  • 然后做同样的事情做一个谷歌搜索..有一个名为.ToArray()的扩展方法你也熟悉linq或lambda表达式..?
  • 我怎么能在谷歌搜索中找到使用这个的例子C# stackoverflow convert tuple&lt;int, int&gt; to an array
  • A) 您的问题似乎是要求将数组的元素转换为元组表示,但您的问题标题实际上与此相反。那么是哪一个呢? B)您提供了代码,但没有提到您当前代码的哪一部分不起作用。我插入了您的代码,它按照我期望的方式工作(除了 x/y 坐标似乎切换了,但这是一个口味问题)。

标签: c# arrays multidimensional-array casting tuples


【解决方案1】:

在 C# 7.0 或更高版本中:

var TestTuple =  (123, "apple", 321) ;

object[] values = TestTuple.ToTuple()
                  .GetType()
                  .GetProperties()
                  .Select(property => property.GetValue(TestTuple.ToTuple()))
                  .ToArray();

【讨论】:

    【解决方案2】:

    如果我理解你的话,你想将Tuple&lt;int, int&gt; 转换成一个数组...

    正如我在对该问题的评论中提到的,MSDN documentation 准确地解释了Tuple&lt;T1, T2&gt; 是什么。 2 元组是 pairKeyValuePair&lt;TKey, TValue&gt; 结构...

    //create a 2-tuple
    Tuple<int, int> t = Tuple.Create(5,11);
    //pass Item1 and Item2 to create an array
    int[] arr = new int[]{t.Item1, t.Item2};
    

    更多详情请见:
    Introduction to Tuples in .NET Framework 4.0
    Overview: Working with Immutable Data

    【讨论】:

    • 真的,你很好地理解了一个如此不清楚以至于示例代码返回类型错误的问题!
    • 谢谢。我觉得 OP 想要将 2 元组转换为数组。 ;)
    【解决方案3】:
    ITuple tuple = (1, "2", 3.4);
    for (int i = 0; i < tuple.Length; i++)
    {
        // use tuple[i] // tuple[i] return object?
    }
    

    ITuple Interface (System.Runtime.CompilerServices) | Microsoft Docs

    【讨论】:

      【解决方案4】:
          T[] values = tuple
              .GetType()
              .GetFields()
              .Select(f => f.GetValue(tuple))
              .Cast<T>()
              .ToArray();
      

      应该给你一个 Ts 数组(假设你的元组包含所有 Ts)!

      【讨论】:

        猜你喜欢
        • 2017-12-01
        • 2014-09-04
        • 1970-01-01
        • 2020-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多