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

4

我需要使用一个接受double[,]的方法,但是我只有一个double[]。如何进行转换?

目前的解决方案:

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

9

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

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

@alexw 很好的发现。我将删除之前的评论。 - shoelzer

7
如果您知道二维数组的宽度,可以使用以下方法将值作为一行接一行地输入。
    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;
    }

1
虽然很容易遵循,但(相对而言)计算成本较高。 - cjbarth
1
Jon Skeet在https://dev59.com/7W435IYBdhLWcg3w7ksK发布了一个性能优化的方法。 - ShawnFeatherly

3

我刚刚写了一段代码,我将使用它:

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

@alexw 很好的发现。我会删除我之前的评论。 - shoelzer

1
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++;
    }
}

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接