将多维数组转换为单一数组列表

4

我有一个多维数组,需要将其转换为数组列表。不是一个单独的数组,而是在第一维的每次迭代中,我都需要一个包含第二维值的单独数组。

如何进行转换:

int[,] dummyArray = new int[,] { {1,2,3}, {4,5,6}};

将两个数组 {1,2,3}{4,5,6} 转化为一个包含两个数组的 list<int[]>

3
在网上搜索时,关键词是“展开”。 - BananaAcid
1
@BananaAcid,但是OP不想要List<int>,他想要List<int[]> - Grundy
@Grundy:没错,但是它应该有多“扁平” - 我相信,示例代码可以进行调整。就像下面的LINQ示例链接一样,只需将其第一个“级别”取出即可。 - BananaAcid
4个回答

4

您可以将二维数组转换为交错数组,然后将其转换为List

int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

int[][] jagged = new int[arr.GetLength(0)][];

for (int i = 0; i < arr.GetLength(0); i++)
{
    jagged[i] = new int[arr.GetLength(1)];
    for (int j = 0; j < arr.GetLength(1); j++)
    {
        jagged[i][j] = arr[i, j];
    }
}

List<int[]> list = jagged.ToList();

4

You can use Linq:

int[,] dummyArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int count = 0;
List<int[]> list = dummyArray.Cast<int>()
                    .GroupBy(x => count++ / dummyArray.GetLength(1))
                    .Select(g => g.ToArray())
                    .ToList();

1
你可以像这样使用for循环:

        int[,] dummyArray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

        int size1 = dummyArray.GetLength(1);
        int size0 = dummyArray.GetLength(0);

        List<int[]> list = new List<int[]>();

        for (int i = 0; i < size0; i++)
        {
            List<int> newList = new List<int>();

            for (int j = 0; j < size1; j++)
            {
                newList.Add(dummyArray[i, j]);
            }

            list.Add(newList.ToArray());
        }

为什么不直接使用数组而是在列表上调用 ToArray?你已经知道长度,它不会改变。 - Grundy

1

这里是一个可重复使用的实现

public static class Utils
{
    public static List<T[]> To1DArrayList<T>(this T[,] source)
    {
        if (source == null) throw new ArgumentNullException("source");
        int rowCount = source.GetLength(0), colCount = source.GetLength(1);
        var list = new List<T[]>(rowCount);
        for (int row = 0; row < rowCount; row++)
        {
            var data = new T[colCount];
            for (int col = 0; col < data.Length; col++)
                data[col] = source[row, col];
            list.Add(data);
        }
        return list;
    }
}

以及示例用法

var source = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
var result = source.To1DArrayList();

关于其他答案的一些评论。

M.kazem Akhgary:如果我需要一个列表,我不明白为什么我应该先创建一个嵌套数组并将其转换列表,而不是直接创建列表

Eser:我通常喜欢他优雅的Linq解决方案,但这绝对不是其中之一。如果想使用Linq(虽然我非常相信它并不是打算这样做),以下解决方案会更合适:

var source = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
var result = Enumerable.Range(0, source.GetLength(0))
    .Select(row => Enumerable.Range(0, source.GetLength(1))
    .Select(col => source[row, col]).ToArray())
    .ToList();

你的回答应该被采纳,我也同意你对其他回答的评论。我先看了那些(因为它们出现在你的上面),我的情绪一直在升温,直到我看到了你的评论。;) - Rob

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