07 Feb 2024




Intermediate

List Generic Collections in C#

Definition:

List<T> is a generic collection class in the System.Collections.Generic namespace of C#. It represents a strongly typed list of objects that can be accessed by index. The T in List<T> represents the type of elements in the list.

Key Features and Characteristics:

  • Dynamic Resizing: Unlike arrays in C# that have a fixed size, List can dynamically grow or shrink in size as elements are added or removed.
  • Generic Type Parameter: The type T within List represents the type of elements that the list can store. This allows you to create a list of any type, whether it's a built-in type like int or string, or a custom class type.
  • Index-based Access: Elements in a List can be accessed by their index, similar to arrays. You can use the square bracket notation ([]) to access elements.
  • Performance: The List data structure provides efficient indexed access to elements and offers constant time complexity O(1) for most operations like adding, removing, and accessing elements by index. However, inserting or removing elements in the middle of the list (which requires shifting subsequent elements) has a time complexity of O(n), where n is the number of elements in the list.
  • Capacity: List internally maintains a capacity, which is the number of elements it can currently store without resizing its internal array. The capacity grows automatically as elements are added to the list, to accommodate more elements efficiently. This helps minimize the frequency of resizing operations, which can be costly in terms of performance.
  • Methods and Properties: List provides a variety of methods and properties for manipulating and accessing its elements. Some common methods include Add, Remove, Insert, Contains, IndexOf, Sort, Clear, ToArray, and more.

Uses:

  • Storing and manipulating collections of objects in memory.
  • Implementing data structures such as stacks, queues, and priority queues.
  • Processing data retrieved from databases or other external sources.
  • Working with collections in LINQ queries and other functional programming paradigms.

Advantages:

  • Type safety ensures that only elements of the specified type can be added to the list.
  • Dynamic resizing allows the list to grow or shrink as needed without manual intervention.
  • Provides efficient random access to elements using indexes.
  • Supports LINQ queries and iteration through its elements.

Disadvantages:

  • Insertion or removal of elements from the middle of the list can be inefficient, as it may require shifting elements.
  • Memory overhead associated with maintaining dynamic resizing.
  • Not suitable for concurrent access from multiple threads without proper synchronization.

Code Examples:

Example 1: Creating and Populating a List

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Creating a list of integers
        List<int> numbers = new List<int>();

        // Adding elements to the list
        numbers.Add(10);
        numbers.Add(20);
        numbers.Add(30);

        // Iterating through the list and printing elements
        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Explanation: This example demonstrates creating a List<int> and populating it with integer values. The Add() method is used to add elements to the list, and then a foreach loop is used to iterate over the list and print its elements.

Example 2: Removing Elements from a List

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<string> names = new List<string>();

        names.Add("Alice");
        names.Add("Bob");
        names.Add("Charlie");

        // Removing an element from the list
        names.Remove("Bob");

        // Iterating through the updated list
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}

Explanation: This example shows how to remove an element ("Bob") from the list using the Remove() method. After removal, the foreach loop is used to iterate over the updated list and print its elements.

Example 3: Finding Elements in a List

using System;
using System.Collections.Generic;

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

        // Finding index of element '30'
        int index = numbers.IndexOf(30);
        Console.WriteLine("Index of 30: " + index); // Output: 2

        // Checking if the list contains an element
        bool contains40 = numbers.Contains(40);
        Console.WriteLine("Contains 40: " + contains40); // Output: True
    }
}

Explanation: This example demonstrates how to find elements in a list using the IndexOf() method to find the index of an element and the Contains() method to check if an element exists in the list.

c-sharp
list
generic-collections