我有一个多维数组,需要将其转换为数组列表。不是一个单独的数组,而是在第一维的每次迭代中,我都需要一个包含第二维值的单独数组。
如何进行转换:
int[,] dummyArray = new int[,] { {1,2,3}, {4,5,6}};
将两个数组
{1,2,3}
和 {4,5,6}
转化为一个包含两个数组的 list<int[]>
?我有一个多维数组,需要将其转换为数组列表。不是一个单独的数组,而是在第一维的每次迭代中,我都需要一个包含第二维值的单独数组。
如何进行转换:
int[,] dummyArray = new int[,] { {1,2,3}, {4,5,6}};
{1,2,3}
和 {4,5,6}
转化为一个包含两个数组的 list<int[]>
?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();
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();
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这里是一个可重复使用的实现
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();
List<int>
,他想要List<int[]>
。 - Grundy