这是一个可重用的实现
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: 如果我需要一个列表,我不明白为什么要先创建锯齿状数组并将其转换 list 而不是直接创建 list。
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();