'Converting a list to a list of list

Is there an elegant way to convert a list to a list of list?

int colCount = 2;
int rowCount = 5;
var src = new List<double>(colCount * rowCount);
var dst = new List<List<double>>(rowCount);
// dst <- src, the elegant way
// ...


Solution 1:[1]

If I've understood you right, you have src List<double> with colCount * rowCount

 var src = new List<double>(colCount * rowCount);

 src.Add(...);
 ...
 src.Add(...); 

and you want to convert src into rectangular List<List<double>> (rowCount items colCount values in each). If it's your case

 var dst = src
   .Select((item, index) => (item, index))
   .GroupBy(pair => pair.index / rowCount, pair => pair.item)
   .Select(group => group.ToList())
   .ToList(); 

If you want just to create dst and fill it with some value (let it be 0.0):

var dst = Enumerable
  .Range(0, rowCount)
  .Select(r => Enumerable
     .Range(0, colCount)
     .Select(c => 0.0)
     .ToList())
  .ToList(); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1