;

C# List<T>


The List<T> in C# is a powerful, versatile, and commonly used collection that belongs to the System.Collections.Generic namespace. It's a generic collection, meaning it enforces type safety while allowing dynamic resizing. In this tutorial, we’ll explore what List<T> is, how to use it effectively, and dive into real-world scenarios and best practices.

Introduction to List<T>

A List<T> is a type-safe, resizable collection that allows you to store and manage a list of objects of a specific type T. Unlike arrays, List<T> automatically adjusts its size when elements are added or removed, making it a suitable choice when the size of the data set is unknown at compile time. The generic nature of List<T> helps enforce type safety, preventing runtime errors by ensuring that only elements of type T can be added.

Why Use List<T>?

  • Type Safety: Ensures that only elements of the specified type can be added.
  • Resizable: Grows dynamically as elements are added or removed.
  • Versatile: Supports various data manipulation methods such as adding, removing, searching, and sorting.

Creating and Initializing a List<T>

Creating a List<T> is straightforward. You need to specify the data type and initialize it with or without elements.

// Initialize an empty list of integers
List<int> numbers = new List<int>();

// Initialize a list with elements
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

The List<T> will expand as elements are added, so there's no need to specify a fixed size like in arrays.

Adding, Accessing, and Modifying Elements

Adding Elements

Elements can be added to a List<T> using the Add or AddRange methods:

List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");

List<string> newNames = new List<string> { "Charlie", "Daisy" };
names.AddRange(newNames);

Accessing Elements

Elements in a List<T> are accessed by their index, similar to arrays.

string firstName = names[0]; // Alice

Modifying Elements

You can modify an element directly by assigning a new value to a specific index.

names[1] = "Robert"; // Changes "Bob" to "Robert"

Removing Elements

The List<T> class provides several methods to remove elements:

  • Remove: Removes the first occurrence of a specified element.
  • RemoveAt: Removes an element at a specified index.
  • RemoveAll: Removes all elements that match a specified condition.
  • Clear: Removes all elements from the list.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Remove(3);         // Removes the first occurrence of 3
numbers.RemoveAt(0);       // Removes the element at index 0
numbers.RemoveAll(n => n > 2); // Removes all elements greater than 2
numbers.Clear();           // Removes all elements from the list

Real-World Example: Inventory Management

Imagine an e-commerce platform where inventory needs to be dynamically managed. Products are constantly added or removed based on stock availability. Using List<T>, we can implement a system to handle this inventory efficiently.

Example

using System;
using System.Collections.Generic;

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }

    public Product(string name, decimal price, int quantity)
    {
        Name = name;
        Price = price;
        Quantity = quantity;
    }

    public override string ToString()
    {
        return $"{Name}: ${Price} (Stock: {Quantity})";
    }
}

public class InventoryManager
{
    private List<Product> products = new List<Product>();

    public void AddProduct(Product product)
    {
        products.Add(product);
    }

    public void RemoveProduct(string productName)
    {
        products.RemoveAll(p => p.Name == productName);
    }

    public void DisplayInventory()
    {
        Console.WriteLine("Inventory:");
        foreach (var product in products)
        {
            Console.WriteLine(product);
        }
    }
}

public class Program
{
    public static void Main()
    {
        InventoryManager inventory = new InventoryManager();

        // Add products to inventory
        inventory.AddProduct(new Product("Laptop", 1200.99m, 10));
        inventory.AddProduct(new Product("Smartphone", 799.99m, 25));
        inventory.AddProduct(new Product("Headphones", 199.99m, 50));

        // Display inventory
        inventory.DisplayInventory();

        // Remove a product and display inventory again
        inventory.RemoveProduct("Smartphone");
        Console.WriteLine("\nAfter Removing Smartphone:");
        inventory.DisplayInventory();
    }
}

Explanation

In this example:

  1. We create a Product class representing items in the inventory, with properties like Name, Price, and Quantity.
  2. The InventoryManager class contains a List<Product> to manage products. It includes methods to add, remove, and display products.
  3. The Main method creates an inventory, adds products, and removes a product, demonstrating dynamic inventory management.

This approach provides a flexible way to manage products in a store, dynamically resizing the list as items are added or removed.

Key Takeaways

  • Type-Safe Flexibility: List<T> enforces type safety, making it a better choice than non-generic collections for holding elements of a single type.
  • Dynamic Resizing: Automatically resizes as elements are added or removed.
  • Rich Set of Methods: Includes a wide range of methods for element manipulation, including Add, Remove, Sort, and Find.
  • Performance Considerations: Suitable for scenarios where data may change dynamically, but performance-sensitive applications may benefit from specific optimizations when resizing frequently.
  • Ideal for Dynamic Collections: Useful in scenarios where data needs to grow or shrink, such as inventory systems, order management, or other collection-based data structures.

Summary

The List<T> in C# is an essential tool for managing collections with dynamic data needs. Its flexibility, type safety, and extensive method set make it the go-to collection for a variety of applications, from simple to complex systems. By leveraging List<T>, developers can efficiently manage and manipulate lists of data in a type-safe, easily manageable way, making it a staple for modern C# programming.