List
, nestedA List
can have elements of List
type. This is a jagged list, similar in syntax to a jagged array. Lists are not by default multidimensional in C#.
To store more complex shapes of data, we can develop multidimensional Lists. We use an easily-developed and expandable data structure.
Consider this shape: the first row has 3 elements, the next row just has 1, and then we have a row with 4 elements. We require a nested list solution that allows this data.
0 1 2 2 1 2 3 4
The C# List
provides an underlying and internal array where it stores its elements. But it always specifies a one-dimensional and zero-based array in its internal structure.
List
will contain an internal array of List
references.foreach
to loop over the inner contents of each List
.using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: add rows and columns to the List. List<List<int>> list = new List<List<int>>(); var rand = new Random(); for (int i = 0; i < 3; i++) { // Put some integers in the inner lists. List<int> sublist = new List<int>(); int top = rand.Next(1, 4); for (int v = 0; v < top; v++) { sublist.Add(rand.Next(1, 5)); } // Add the sublist to the top-level List. list.Add(sublist); } // Display the List. Display(list); } static void Display(List<List<int>> list) { // Part 2: loop over and display everything in the List. Console.WriteLine("Elements:"); foreach (var sublist in list) { foreach (var value in sublist) { Console.Write(value); Console.Write(' '); } Console.WriteLine(); } // Part 3: display element. Console.WriteLine("Element at 1, 0:"); Console.WriteLine(list[1][0]); // Part 4: display total count. int count = 0; foreach (var sublist in list) { count += sublist.Count; } Console.WriteLine("Count:"); Console.WriteLine(count); } }Elements: 1 3 2 2 2 2 Element at 1, 0: 2 Count: 6
As for performance, a nested List
is relatively fast. It internally uses zero-based arrays, and the List
type itself is fast.
class
may be desirable.List
into a separate class
. This could be better for real-world programs.We used a nested List
that is essentially a jagged or 2D List
data type with the generic List
class
. The code here is not ideal. But it helps in prototyping or experimental work.