Shlomi Komemi
Shlomi Komemi

Reputation: 5545

How to convert List<List<int>> to an array of arrays

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

Answers (5)

kaszm
kaszm

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

Khelvaster
Khelvaster

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

Chamika Sandamal
Chamika Sandamal

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

svick
svick

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 fors.

Upvotes: 6

Alex Bagnolini
Alex Bagnolini

Reputation: 22382

int[][] arrays = lst.Select(a => a.ToArray()).ToArray();

Upvotes: 75

Related Questions