What is the best way to convert a list into an array of type int[][]
?
List<List<int>> lst = new List<List<int>>();
int[][] arrays = lst.Select(a => a.ToArray()).ToArray();
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.
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.
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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.