c sharp

How to use Multidimensional Lists in C#

In C#, a multidimensional list is a collection of elements that is organized in a two-dimensional or three-dimensional array. This collection makes it simpler to handle and evaluate vast volumes of data by allowing you to store and manipulate data in a table-like style. Multidimensional lists are used in various applications, from scientific computing to game development. We will go through the fundamentals of multidimensional lists in C#, their syntax, and several usage examples in this post.

Multidimensional List in C#

In C#, multidimensional lists are represented as arrays with two or more dimensions. The syntax for creating a two-dimensional array is as follows:

List<List<T>> list = new List<List<T>>();

Here, T represents the type of elements that the list will contain. The outer List<T> represents the rows of the table, and the inner List<T> represents the columns of each row.

To add a new row to the list, you can use the Add method of the outer list, followed by a new instance of the inner list to represent the columns of that row. To add a new element to a specific cell in the table, you can use the Add method of the appropriate inner list, specifying the value to be added.

How to use Multidimensional List in C#

To use a multidimensional list in C#, you must first create an instance of the array and initialize it with values. Here’s an example of how to create a two-dimensional list:

List<List<T>> listName = new List<List<T>>(rowCount);

for (int i = 0; i < rowCount; i++)
{
    listName.Add(new List<T>(columnCount));
   
    for (int j = 0; j < columnCount; j++)
    {
        listName[i].Add(default(T));
    }
}

Here, T represents the type of elements to be stored in the list, rowCount represents the number of rows in the list, and columnCount represents the number of columns in the list. With this syntax, a list of lists is created, with the outer list containing all the rows and the inner lists each representing a row of the multidimensional list. To add values to a multidimensional list in C#, you can use the following syntax:

list[rowIndex][columnIndex] = value;

Here, the list is multidimensional, rowIndex is the index of the row where you want to add the value, columnIndex is the index of the column where you want to add the value, and value is the value you want to add.

Here is the complete example code that illustrates using of a multidimensional list in C# that creates a 2-D list, modifies it, and shows how to access any element in the list:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // create a 3x3 table of integers using a multidimensional list
        List<List<int>> table = new List<List<int>>(3);

        for (int i = 0; i < 3; i++)
        {
            table.Add(new List<int>(3));

            for (int j = 0; j < 3; j++)
            {
                table[i].Add(i);
            }
        }
        // set some values in the table
        table[0][0] = 1;
        table[1][1] = 2;
        table[2][2] = 3;
        // print the table
        for (int i = 0; i < table.Count; i++)
        {
            for (int j = 0; j < table.Count; j++)
            {
                Console.Write(table[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}

This C# code creates a 3×3 table of integers using a multidimensional list. It first initializes the list with empty lists using the constructor and then adds integers with a nested loop. After that, it sets some values in the table at positions [0, 0], [1, 1], and [2, 2]. Finally, it prints the table by iterating through the list with two nested loops and printing the values at each index.

Here is yet another case of multidimensional list usage in C#. The code creates a 2×2 table of strings and then demonstrates how to add an element, remove an element, and access an element in the list:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // create a 2x2 table of strings using a multidimensional list
        List<List<string>> table = new List<List<string>>(2);

        for (int i = 0; i < 2; i++) {
            table.Add(new List<string>(2));

            for (int j = 0; j < 2; j++) {
                table[i].Add($"[{i},{j}]");
            }
        }

        // print original list
        Console.WriteLine("Original list:");
        PrintTable(table);

        // add an element to the table
        table[1].Insert(1, "[1,1]");

        // print updated list after adding an element
        Console.WriteLine("\nUpdated list after adding an element:");
        PrintTable(table);

        // remove an element from the table
        table[0].RemoveAt(0);

        // print updated list after removing an element
        Console.WriteLine("\nUpdated list after removing an element:");
        PrintTable(table);

        // access an element in the table
        string element = table[1][0];

        Console.WriteLine($"\nAccessed element: {element}");
    }

    static void PrintTable(List<List<string>> table) {
        for (int i = 0; i < table.Count; i++) {
            for (int j = 0; j < table[i].Count; j++) {
                Console.Write(table[i][j] + " ");
            }

            Console.WriteLine();
        }
    }
}

This code creates a 2×2 table of strings using a multidimensional list and initializes it with values. Then, it prints the original list using the PrintTable method. Next, it adds an element to the second row of the table using the Insert method. After that, it prints the updated list using PrintTable. Then, it removes an element from the first row of the table using the RemoveAt method and prints the updated list again. Finally, it accesses an element in the table using the square bracket notation and prints it. The output will be formatted as follows:

Conclusion

Multidimensional lists are an essential feature of C# that allows you to store and manipulate data in a table-like format. With the help of multidimensional lists, you can efficiently manage large amounts of data and perform complex calculations. Multidimensional lists can be useful in a wide range of applications, from representing matrices in linear algebra to storing data in a spreadsheet-like format.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.