How to convert List> to an array of arrays

后端 未结 4 713
刺人心
刺人心 2020-12-08 19:40

What is the best way to convert a list into an array of type int[][]?

List> lst = new List>();


        
相关标签:
4条回答
  • 2020-12-08 20:02

    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

    0 讨论(0)
  • 2020-12-08 20:07

    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!

    0 讨论(0)
  • 2020-12-08 20:09
    int[][] arrays = lst.Select(a => a.ToArray()).ToArray();
    
    0 讨论(0)
  • 2020-12-08 20:13

    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.

    0 讨论(0)
提交回复
热议问题