C# Nested List

List type

A List can have List elements.
This is a sort of jagged list:
it is similar in syntax
and usage to a jagged array. In this way we can develop multidimensional Lists. This yields an easily-developed and expandable data structure.

Jagged Arrays

Example

The List generic type in the C# language provides an underlying and internal array where it stores its elements. However, it always specifies a one-dimensional and zero-based array in its internal structure.

ArrayTwo-dimensional: 2D

Note:When you create a List whose element type is another List, the first List will contain an internal array of List references.

And:The List objects these references point to are separate. They will contain one-dimensional arrays.

Program that uses nested Lists: C#

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	//
	// Add rows and columns to the List.
	//
	List<List<int>> list = new List<List<int>>();
	var rand = new Random();
	for (int i = 0; i < 10; i++)
	{
	    //
	    // Put some integers in the inner lists.
	    //
	    List<int> sublist = new List<int>();
	    int top = rand.Next(1, 15);
	    for (int v = 0; v < top; v++)
	    {
		sublist.Add(rand.Next(1, 5));
	    }
	    //
	    // Add the sublist to the top-level List reference.
	    //
	    list.Add(sublist);
	}
	//
	// Display the List.
	//
	Display(list);
    }

    static void Display(List<List<int>> list)
    {
	//
	// 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();
	}
	//
	// Display element at 3, 3.
	//
	if (list.Count > 3 &&
	    list[3].Count > 3)
	{
	    Console.WriteLine("Element at 3, 3:");
	    Console.WriteLine(list[3][3]);
	}
	//
	// Display total count.
	//
	int count = 0;
	foreach (var sublist in list)
	{
	    count += sublist.Count;
	}
	Console.WriteLine("Count:");
	Console.WriteLine(count);
    }
}

Output

Elements:
4 2 4 1
2 1 3
2 4 2 4 3 3 1
4 2 4 1 2 1 2
1 3 4 4
3 2 4 2 1 2 4
4 3 1 4 3 4 4 3
2 1 4 1 2 4 1
3 2 2
1 3 1 4 1 4 2 2 3 2 1 2
Element at 3, 3:
1
Count:
62
Var keyword

In this example, the List type signature used has confusing syntax because it must specify nested type parameters. You can sometimes simplify this syntax by using the implicit typing provided by the var-keyword.

Var

So:The Main method first creates a List instance. It then populates it with ten new List instances as its elements.

And:Those latter List instances are initialized with a random number of random integers.

RandomIntMethod call

The Display method receives a parameter of type List<List<int>>. In the method signature, you must type out the entire type exactly. Keep in mind that nested List types with specific inner type parameters are unique.

Tip:The Display method uses the foreach-loop syntax to loop over the inner contents of each List.

Foreach

Next, the Display method also shows how to access a specific element such as one at indexes {3, 3} in the 2-dimensional List type. You must be careful to check the Count property on each List separately.

Finally:The example counts all the elements together and displays that figure with Console.WriteLine.

Console.WriteLine

Discussion

Programming tip

A nested List type is relatively fast. It internally uses zero-based arrays, and the List type itself is fast. But adding another layer of abstraction and creating a nested class may be desirable.

Note:This can help reduce the amount of complexity and syntax confusion at the calling sites.

Tip:Another option is to encapsulate the List<List<T>> into a separate class. This could be better for real-world programs.

Class

Summary

The C# programming language

We explored how you can use 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 is fine for prototyping or experimental work.

Also:We saw how to loop over 2D List instances and sum all the elements in this data structure.


C#: Collections: List