Reputation: 5545
What is the best way to convert a list into an array of type int[][]
?
List<List<int>> lst = new List<List<int>>();
Upvotes: 39
Views: 34910
Reputation: 51
If you don't have any restriction on using List<int[]>
instead of List<List<int>>
than use List<int[]>
and then convert it into array of array using .ToArray()
at end of list object.
Example for first converting List<List<int>>
to List<int[]>
List<int[]> listOfArray=new List<int[]>();
List<List<int>> yourList=[someValue];
foreach(var listItem in yourList){
listOfArray.Add(listItem.ToArray());
}
Example For List<int[]>
to int[][]
:
int[][] jaggedArray= listOfArray.ToArray(); //voila you get jagged array or array of array
Upvotes: -1
Reputation: 872
There's no library function to do this.
You'll need to do this with loops.
int[][] newlist = new int[lst.Size][];
for (int i = 0; i < lst.Size; i++)
{
List<int> sublist = lst.ElementAt(i);
newlist[i] = new int[sublis.Size];
for (int j = 0; j < sublist.Size; j++)
{
newlist[i][j] = sublist.ElementAt(j);
}
}
There you go!
Upvotes: -1
Reputation: 24302
you can easily do it using linq.
int[][] arrays = lst.Select(a => a.ToArray()).ToArray();
but if you want another way you can loop through the list and manually generate the 2d array.
how to loop through nested list
Upvotes: 2
Reputation: 244757
It's easy with LINQ:
lst.Select(l => l.ToArray()).ToArray()
If you really wanted two-dimentional array (int[,]
, not int[][]
), that would be more difficult and the best solution would probably be using nested for
s.
Upvotes: 6