Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 2D array to a 2D list in C#

I have a 2D string array. I want to convert this into

List<List<string>>

How do I achieve this in C#?

like image 354
Rama Avatar asked May 26 '16 10:05

Rama


2 Answers

Using Linq you could do this.

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();

check this example

like image 171
Hari Prasad Avatar answered Sep 30 '22 22:09

Hari Prasad


Another way is to use the LINQ equivalent of a nested for loops:

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();
like image 40
Ivan Stoev Avatar answered Sep 30 '22 21:09

Ivan Stoev