如何在C#中将2D数组转换为2D列表

Ram*_*ama 2 c# list multidimensional-array

我有一个2D字符串数组.我想把它转换成

List<List<string>>
Run Code Online (Sandbox Code Playgroud)

我如何在C#中实现这一目标?

Har*_*sad 6

使用Linq你可以做到这一点.

var result list.Cast<string>() 
            .Select((x,i)=> new {x, index = i/list.GetLength(1)})  // Use overloaded 'Select' and calculate row index.
            .GroupBy(x=>x.index)                                   // Group on Row index
            .Select(x=>x.Select(s=>s.x).ToList())                  // Create List for each group.  
            .ToList();
Run Code Online (Sandbox Code Playgroud)

检查一下 example


Iva*_*oev 5

另一种方法是使用 LINQ 等效的嵌套for循环:

string[,] array = { { "00", "01", "02"}, { "10", "11", "12" } };

var list = Enumerable.Range(0, array.GetLength(0))
    .Select(row => Enumerable.Range(0, array.GetLength(1))
    .Select(col => array[row, col]).ToList()).ToList();
Run Code Online (Sandbox Code Playgroud)