C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Var: You can sometimes simplify this syntax by using the implicit typing provided by the var-keyword.
VarDisplay: This method receives a parameter of type List<List<int>>. It uses the foreach-loop syntax to loop over the inner contents of each List.
ForeachConsoleC# program that uses nested Lists
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
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