Home C# Tutorial on List in C#

Tutorial on List in C#

The List<T> class in C# is a part of the System.Collections.Generic namespace and provides a dynamic array for storing collections of objects.

List<T> allows you to store, retrieve, and manipulate collections of objects, with dynamic resizing as items are added or removed.

It is one of the most commonly used collection types in C# due to its versatility and ease of use.

In this tutorial, we’ll cover:

1. Creating a List<T>

To create a List<T>, include the System.Collections.Generic namespace. T is the type parameter representing the type of elements in the list, such as int, string, or a custom class.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        // Create a list of integers
        List<int> numbers = new List<int>();

        // Create a list of strings with initial values
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        Console.WriteLine("Initial names list:");
        foreach (string name in names) {
            Console.WriteLine(name);
        }
    }
}

Output:

Initial names list:
Alice
Bob
Charlie

In this example:

  • List<int> numbers = new List<int>(); creates an empty list of integers.
  • List<string> names = new List<string> { “Alice”, “Bob”, “Charlie” }; initializes a list of strings with values.

2. Adding Elements to a List

You can add elements to a list using the Add, AddRange, or Insert methods.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int>();

        // Adding individual elements
        numbers.Add(10);
        numbers.Add(20);
        numbers.Add(30);

        // Adding multiple elements
        numbers.AddRange(new int[] { 40, 50, 60 });

        // Inserting an element at a specific index
        numbers.Insert(1, 15); // Insert 15 at index 1

        Console.WriteLine("Numbers list:");
        foreach (int number in numbers) {
            Console.WriteLine(number);
        }
    }
}

Output:

Numbers list:
10
15
20
30
40
50
60

In this example:

  • Add(10) adds 10 to the end of the list.
  • AddRange(new int[] { 40, 50, 60 }) adds multiple elements to the list.
  • Insert(1, 15) inserts 15 at index 1, shifting existing elements to the right.

3. Accessing and Modifying Elements

You can access elements in a List<T> using an index, similar to arrays. You can also modify elements by assigning a new value at a specific index.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        // Access elements by index
        Console.WriteLine("First name: " + names[0]);

        // Modify an element
        names[1] = "Robert";

        Console.WriteLine("Modified names list:");
        foreach (string name in names) {
            Console.WriteLine(name);
        }
    }
}

Output:

First name: Alice
Modified names list:
Alice
Robert
Charlie

In this example:

  • names[1] = “Robert”; modifies the element at index 1.

4. Removing Elements

You can remove elements from a list using methods like Remove, RemoveAt, RemoveRange, and Clear.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 10, 20, 30, 40, 50, 60 };

        // Remove a specific element by value
        numbers.Remove(30);

        // Remove an element by index
        numbers.RemoveAt(2); // Removes element at index 2

        // Remove a range of elements
        numbers.RemoveRange(1, 2); // Removes two elements starting from index 1

        Console.WriteLine("Modified numbers list:");
        foreach (int number in numbers) {
            Console.WriteLine(number);
        }
    }
}

Output:

Modified numbers list:
10
60

In this example:

  • Remove(30) removes the first occurrence of 30.
  • RemoveAt(2) removes the element at index 2.
  • RemoveRange(1, 2) removes two elements starting from index 1.

5. Searching and Filtering

The Contains, IndexOf, Find, and FindAll methods help with searching and filtering items in a list.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 10, 20, 30, 40, 50, 60 };

        // Check if a value exists in the list
        bool has30 = numbers.Contains(30);
        Console.WriteLine("Contains 30: " + has30);

        // Get the index of a specific element
        int index40 = numbers.IndexOf(40);
        Console.WriteLine("Index of 40: " + index40);

        // Find the first element greater than 25
        int firstAbove25 = numbers.Find(n => n > 25);
        Console.WriteLine("First number greater than 25: " + firstAbove25);

        // Find all elements greater than 25
        List<int> above25 = numbers.FindAll(n => n > 25);
        Console.WriteLine("Numbers greater than 25:");
        foreach (int n in above25) {
            Console.WriteLine(n);
        }
    }
}

Output:

Contains 30: True
Index of 40: 3
First number greater than 25: 30
Numbers greater than 25:
30
40
50
60

In this example:

  • Contains(30) checks if 30 is in the list.
  • IndexOf(40) finds the index of 40.
  • Find(n => n > 25) finds the first number greater than 25.
  • FindAll(n => n > 25) finds all numbers greater than 25.

6. Commonly Used Methods

Here are some additional useful methods for working with List<T>:

  • Count: Gets the number of elements in the list.
  • Sort: Sorts the elements in the list.
  • Reverse: Reverses the order of elements.
  • ToArray: Converts the list to an array.
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 50, 20, 40, 10, 30 };

        // Count the elements
        Console.WriteLine("Number of elements: " + numbers.Count);

        // Sort the list
        numbers.Sort();
        Console.WriteLine("Sorted list:");
        foreach (int number in numbers) {
            Console.WriteLine(number);
        }

        // Reverse the list
        numbers.Reverse();
        Console.WriteLine("Reversed list:");
        foreach (int number in numbers) {
            Console.WriteLine(number);
        }

        // Convert list to array
        int[] numbersArray = numbers.ToArray();
        Console.WriteLine("Array from list:");
        foreach (int number in numbersArray) {
            Console.WriteLine(number);
        }
    }
}

Output:

Number of elements: 5
Sorted list:
10
20
30
40
50
Reversed list:
50
40
30
20
10
Array from list:
50
40
30
20
10

7. Iterating Through a List<T>

You can iterate through a list using a foreach loop or a for loop.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

        // Using foreach loop
        Console.WriteLine("Using foreach loop:");
        foreach (string name in names) {
            Console.WriteLine(name);
        }

        // Using for loop
        Console.WriteLine("Using for loop:");
        for (int i = 0; i < names.Count; i++) {
            Console.WriteLine(names[i]);
        }
    }
}

Output:

Using foreach loop:
Alice
Bob
Charlie
Using for loop:
Alice
Bob
Charlie

Summary

In this tutorial, we covered the List<T> class in C# and demonstrated its features:

  1. Creating a List<T>: Initializing lists with or without values.
  2. Adding Elements: Using Add, AddRange, and Insert to add items.
  3. Accessing and Modifying Elements: Accessing by index and modifying elements.
  4. Removing Elements: Removing specific items, items by index, or ranges.
  5. Searching and Filtering: Using Contains, IndexOf, Find, and FindAll.
  6. Commonly Used Methods: Methods like Count, Sort, Reverse, and ToArray.
  7. Iterating Through Lists: Using foreach and for loops.

The List<T> class is a versatile and powerful collection type in C# that simplifies working with dynamically sized collections.

 

You may also like