如何将单维数组转换为多维数组? (C#)

时间:2009-07-25 20:32:04

标签: c# .net arrays multidimensional-array

我必须使用一个接受double [,]的方法,但我只有一个double []。我该如何转换它?

到目前为止的解决方案:

var array = new double[1, x.Length];
foreach (var i in Enumerable.Range(0, x.Length))
{
    array[0, i] = x;
}

4 个答案:

答案 0 :(得分:8)

没有直接的方法。您应该将内容复制到double[,]。假设你想要它在一行:

double[,] arr = new double[1, original.Length];
for (int i = 0; i < original.Length; ++i) 
    arr[0, i] = original[i];

答案 1 :(得分:6)

如果您知道2D数组的宽度,可以使用以下内容将值一个接一个地放在另一行中。

    private T[,] toRectangular<T>(T[] flatArray, int width)
    {
        int height = (int)Math.Ceiling(flatArray.Length / (double)width);
        T[,] result = new T[height, width];
        int rowIndex, colIndex;

        for (int index = 0; index < flatArray.Length; index++)
        {
            rowIndex = index / width;
            colIndex = index % width;
            result[rowIndex, colIndex] = flatArray[index];
        }
        return result;
    }

答案 2 :(得分:2)

我刚刚编写了这段代码,我将使用:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace MiscellaneousUtilities
{
    public static class Enumerable
    {
        public static T[,] ToRow<T>(this IEnumerable<T> target)
        {
            var array = target.ToArray();
            var output = new T[1, array.Length];
            foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
            {
                output[0, i] = array[i];
            }
            return output;
        }

        public static T[,] ToColumn<T>(this IEnumerable<T> target)
        {
            var array = target.ToArray();
            var output = new T[array.Length, 1];
            foreach (var i in System.Linq.Enumerable.Range(0, array.Length))
            {
                output[i, 0] = array[i];
            }
            return output;
        }
    }
}

答案 3 :(得分:0)

Mehrdad假设宽度为1,因为没有真正的方法来确定一维数组本身的宽度或高度。如果你有'宽度'的某些(外部)概念,那么Mehrdad的代码变为:

// assuming you have a variable with the 'width', pulled out of a rabbit's hat
int height = original.Length / width;
double[,] arr = new double[width, height];
int x = 0;
int y = 0;
for (int i = 0; i < original.Length; ++i)
{
    arr[x, y] = original[i];
    x++;
    if (x == width)
    {
        x = 0;
        y++;
    }
}

虽然 Row major 在许多应用程序(矩阵,文本缓冲区或图形)中可能更常见:

// assuming you have a variable with the 'width', pulled out of a rabbit's hat
int height = original.Length / width;
double[,] arr = new double[height, width]; // note the swap
int x = 0;
int y = 0;
for (int i = 0; i < original.Length; ++i)
{
    arr[y, x] = original[i]; // note the swap
    x++;
    if (x == width)
    {
        x = 0;
        y++;
    }
}