尝试使用C#将int []转换为int [,]

mou*_*iec 5 c# arrays multidimensional-array

我想要一个函数将单维数组int [480000]转换为大小为int [800,600]的二维数组.你能帮我解决一下如何做到这一点吗?

Jar*_*dek 5

public static T[,] Convert<T>(this T[] source, int rows, int columns)
{
  int i = 0;
  T[,] result = new T[rows, columns];

  for (int row = 0; row < rows; row++)
    for (int col = 0; col < columns; col++)
      result[row, col] = source[i++];
  return result;
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 5

你真的想要物理移动数据还是800x600的"View"就足够了?
您可以使用这样的包装器:

// error checking omitted
class MatrixWrapper<T>
{
    private T[] _data;
    private int _columns;

    public MatrixWrapper(T[] data, int rows, int columns)
    {
        _data = data;
        _columns = columns;
        // validate rows * columns == length
    }

    public T this[int r, int c]
    {
        get { return _data[Index(r, c)]; }
        set { _data[Index(r, c)] = value; }
    }

    private int Index(int r, int c)
    {
        return r * _columns + c;
    }
}
Run Code Online (Sandbox Code Playgroud)

你使用它像:

        double[] data = new double[4800];
        var wrapper = new MatrixWrapper<double>(data, 80, 60);
        wrapper[2, 2] = 2.0;
Run Code Online (Sandbox Code Playgroud)