Convert a List of Lists to a 2D array in C#
This post will discuss how to convert a List of Lists to a 2D array in C#.
You can use LINQ to convert a List<List<T>> into a two-dimensional array T[][]. The following code example uses the Select() method to project each list into an array with the help of the ToArray() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<List<string>> lists = new List<List<string>>() { new List<string>() { "C", "C++" }, new List<string>() { "Java", "C#", "Kotlin" } }; string[][] arrays = lists.Select(a => a.ToArray()).ToArray(); // print the 2D array foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } } |
Output:
C, C++
Java, C#, Kotlin
If you need a T[,] instead, the best solution would probably be to loop through the list using nested loops and explicitly generate the 2D array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<List<string>> lists = new List<List<string>>() { new List<string>() { "C", "C++" }, new List<string>() { "Java", "Kotlin" } }; string[,] arrays = new string[lists.Count, lists[0].Count]; for (int i = 0; i < lists.Count; i++) { for (int j = 0; j < lists[i].Count; j++) { arrays[i,j] = lists[i][j]; } } // print the 2D array foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } } |
Output:
C
C++
Java
Kotlin
That’s all about converting a List of Lists to a 2D array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)