如何在 C# 中将元组转换为数组?

问题描述 投票:0回答:5

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

这是数组:

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# arrays multidimensional-array casting tuples
5个回答
7
投票

在 C# 7.0 或更高版本中:

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

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

3
投票

如果我很了解你的话,你想将

Tuple<int, int>
转换为数组...

正如我在问题评论中提到的,MSDN 文档 准确解释了

Tuple<T1, T2>
是什么。 2 元组是一个 pair
KeyValuePair<TKey, TValue>
结构...

//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};

更多详情请参阅:
.NET Framework 4.0 中的元组简介
概述:使用不可变数据


2
投票
ITuple tuple = (1, "2", 3.4);
for (int i = 0; i < tuple.Length; i++)
{
    // use tuple[i] // tuple[i] return object?
}

ITuple 接口(System.Runtime.CompilerServices)|微软文档


0
投票
    T[] values = tuple
        .GetType()
        .GetFields()
        .Select(f => f.GetValue(tuple))
        .Cast<T>()
        .ToArray();

应该为您提供一个 T 数组(假设您的元组包含所有 T)!


0
投票

对于旧的

Tuple
和新的
ValueTuple
类型,都有一个通用接口
ITuple
,它提供了处理它们的任何可能长度所需的功能。

这里是将任何元组转换为

object
数组的扩展方法的可能解决方案:

public static object[] ToArray(this System.Runtime.CompilerServices.ITuple tuple)
{
    var array = new object[tuple.Length];

    for (var index = 0; index < tuple.Length; index++)
    {
        array[index] = tuple[index];
    }

    return array;
}

或者无需分配数组即可实现

IEnumerable<object>
的另一种解决方案:

public static IEnumerable<object> AsEnumerable(this System.Runtime.CompilerServices.ITuple tuple)
{
    for (var index = 0; index < tuple.Length; index++)
        yield return tuple[index];
}
© www.soinside.com 2019 - 2024. All rights reserved.