Converting int[][] to List<List<int>>

64 Views Asked by At

I need to convert an array int[][] to List<List<int>>. Is it possible and how?

Array[index].Length can be 0.

First, i tried to do like this: List<List<int>> ListName = new List<List<int>>(ArrayName); but it didn't work. Then, I tried to use LINQ like List<List<int>> ListName = ArrayName.OfType<List<int>>().ToList(); but it also didn't work. I searched in internet about this, but everywhere articles are saying about converting int[] to List<int>.

2

There are 2 best solutions below

0
Haney On BEST ANSWER

articles are saying about converting int[] to List<int>

That's the right idea, but you need to do it for the inner and outer arrays. Something like this:

var newList = new List<List<int>>(originalList.Length);

foreach (var item in originalList)
{
    newList.Add(new List<int>(item));
}

That should get you what you need!

0
MintChoco On

how about this..

int[][] array = new int[][] {
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 },
    new int[] { 6 }
};

List<List<int>> list = array.Select(row => row.ToList()).ToList();

:-)