Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to convert nested list to array in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<List<int>> nestedList = new List<List<int>>         {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 }
        };

        // Convert the nested list to a 2D array
        int[,] array = ConvertNestedListToArray(nestedList);

        for (int i = 0; i < array.GetLength(0); i++) {
            for (int j = 0; j < array.GetLength(1); j++) {
                Console.Write(array[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

    static int[,] ConvertNestedListToArray(List<List<int>> nestedList) {
        // Get the number of rows and columns
        int rows = nestedList.Count;
        int cols = nestedList[0].Count;

        // Initialize the 2D array
        int[,] array = new int[rows, cols];

        // Populate the array with values from the nested list
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                array[i, j] = nestedList[i][j];
            }
        }

        return array;
    }
}

 
/*
run:
     
1 2 3 
4 5 6 
7 8 9 
 
*/

 



answered Mar 31, 2025 by avibootz
...