Create a List of Lists in C#
This post will discuss how to create a List of Lists in C#.
A simple solution for constucting a List of Lists is to create the individual lists and use the List<T>.Add(T) method to add them to the main list. The following example demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> lang1 = new List<string>() { "C", "C++" }; List<string> lang2 = new List<string>() { "Java", "C#" }; List<List<string>> listOfLists = new List<List<string>>(); listOfLists.Add(lang1); listOfLists.Add(lang2); foreach (var list in listOfLists) { Console.WriteLine(String.Join(", ", list)); } } } |
Output:
C, C++
Java, C#
This is equivalent to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<string> lang1 = new List<string>() { "C", "C++" }; List<string> lang2 = new List<string>() { "Java", "C#" }; List<List<string>> listOfLists = new List<List<string>>() { lang1, lang2 }; foreach (var list in listOfLists) { Console.WriteLine(String.Join(", ", list)); } } } |
Output:
C, C++
Java, C#
That’s all about creating a List of Lists 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 :)