将 int[][] 转换为列表<List<int>> [重复]

问题描述 投票:0回答:2

我需要将数组

int[][]
转换为
List<List<int>>
。这可能吗?如何?

Array[index].Length
可以是 0.

首先,我尝试这样做:

List<List<int>> ListName = new List<List<int>>(ArrayName);
但它没有用。然后,我尝试像
List<List<int>> ListName = ArrayName.OfType<List<int>>().ToList();
一样使用LINQ,但它也没有用。我在互联网上搜索过这个,但到处都有文章说将
int[]
转换为
List<int>
.

c# arrays list jagged-arrays
2个回答
0
投票

文章说将

int[]
转换为
List<int>

这个想法是对的,但是你需要对内部和外部数组这样做。像这样的东西:

var newList = new List<List<int>>(originalList.Length);

foreach (var item in originalList)
{
    newList.Add(new List<int>(item));
}

这应该可以满足您的需求!


0
投票

这个怎么样..

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

List<List<int>> list = array.Select(row => row.ToList()).ToList();

:-)

© www.soinside.com 2019 - 2024. All rights reserved.