Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn a Tuple into an Array in C#?

I can't find anything about this so I'm not sure if it is possible but I have a tuple that contains the coordinates of an element in a two-dimensional array. I want to be able to find the distance between elements in a two-dimensional array and to do this I want the position of the element in one dimensional array form (I'm not sure of a better way to do this). So is it possible to turn a Tuple into an array?

This is the array:

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

This is the method I used to get the coordinates of an element in a multidimensional array:

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);
    }
like image 456
user3124306 Avatar asked Sep 19 '25 02:09

user3124306


1 Answers

In C# 7.0 or above:

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

object[] values = TestTuple.ToTuple()
                  .GetType()
                  .GetProperties()
                  .Select(property => property.GetValue(TestTuple.ToTuple()))
                  .ToArray();
like image 55
Steven Chou Avatar answered Sep 20 '25 17:09

Steven Chou