Light Mode Image

C# List

A List is a dynamic array that can grow or shrink in size. It is part of the System.Collections.Generic namespace.

 

Example of a list in C#.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating a List of integers
        List<int> myList = new List<int>();

        // Adding elements to the List
        myList.Add(10);
        myList.Add(20);
        myList.Add(30);

        // Accessing elements by index
        Console.WriteLine("First element: " + myList[0]); // Output: 10

        // Iterating through the List
        Console.WriteLine("List elements:");
        foreach (int item in myList)
        {
            Console.WriteLine(item);
        }

        // Count of elements in the List
        Console.WriteLine("Number of elements: " + myList.Count); // Output: 3

        // Removing an element
        myList.Remove(20);

        // Check if an element exists in the List
        Console.WriteLine("Contains 20? " + myList.Contains(20)); // Output: False

        // Clear all elements from the List
        myList.Clear();

        // Check if the List is empty
        Console.WriteLine("Is the list empty? " + (myList.Count == 0)); // Output: True
    }
}

 

In this example, we create a list of integers (List<int>), add elements, access elements by index, iterate through the list, remove elements, check for the existence of an element, and clear the entire list.

 

The List<T> class provides various methods and properties for working with lists, making it a versatile and commonly used data structure in C#.