I have a 2D string array. I want to convert this into
List<List<string>>
How do I achieve this in C#?
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With