Working with Lists in C#: A Comprehensive Guide to the `List` Class
Master the C# `List` class for efficient and flexible data storage. This tutorial covers list creation, adding and removing elements, accessing elements using indexers, iterating through lists, and utilizing collection initializers for concise list population.
Working with Lists in C#
The C# `List
Key Features of `List`
- Dynamic Size: The list's size can grow or shrink as elements are added or removed.
- Duplicate Elements Allowed: You can store multiple instances of the same element.
- Random Access: Access elements by their index using square bracket notation (e.g., `myList[0]`).
- Easy Element Manipulation: Methods like `Add()`, `Insert()`, `Remove()`, `RemoveAt()` make it simple to work with list elements.
Example 1: Adding Elements Using `Add()`
using System;
using System.Collections.Generic;
public class ListExample {
public static void Main(string[] args) {
List<string> names = new List<string>();
// Add elements to the list
names.Add("Alice");
names.Add("Bob");
// ... (code to iterate and print elements) ...
}
}
Example 2: Using Collection Initializers
Collection initializers provide a concise way to create and populate a list:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };