C# List<T>: A Comprehensive Guide with Examples
The List<T> class in C# is one of the most versatile and commonly used collection types. It belongs to the System.Collections.Generic namespace and provides a dynamic, type-safe way to store and manage collections of items. Whether you're working with simple data types like integers or complex objects, List<T> offers a wide range of features to make your coding experience efficient and hassle-free.
In this guide, we’ll explore the List<T> class in detail, covering its key characteristics, common operations, and practical examples to help you master its usage.
What is List<T> in C#?
The List<T> class is a generic collection that allows you to store and manipulate a list of items of a specified type (T). Unlike arrays, which have a fixed size, List<T> can dynamically grow or shrink as you add or remove elements. This makes it an ideal choice for scenarios where the number of elements is not known in advance.
Key Characteristics of List<T>
- Dynamic Sizing: Automatically resizes itself as elements are added or removed.
- Type Safety: Ensures that only elements of the specified type (T) can be added to the list.
- Index-Based Access: Allows you to access elements using zero-based indexing, just like arrays.
- Efficient Operations: Provides fast insertion, deletion, and access to elements.
- Range Operations: Supports adding, inserting, and removing multiple elements at once.
- Sorting and Searching: Built-in methods for sorting and searching elements.
- LINQ Support: Works seamlessly with LINQ for querying and transforming data.
- Memory Management: Handles memory allocation and resizing internally for optimal performance.
How to Use List<T> in C#
Let’s dive into the practical aspects of using List<T> with step-by-step examples.
1. Import the Required Namespace
Before using List<T>, you need to include the System.Collections.Generic namespace in your code:
using System.Collections.Generic;
2. Create a List
To create a list, specify the type of elements it will hold. For example, to create a list of integers:
List<int> numbers = new List<int>();
You can also initialize a list with some initial values:
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" };
3. Add Elements to the List
Use the Add method to append elements to the list:
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
To add multiple elements at once, use the AddRange method:
numbers.AddRange(new int[] { 40, 50, 60 });
4. Insert Elements at a Specific Position
The Insert method allows you to add an element at a specific index:
List<string> colors = new List<string> { "Red", "Green", "Blue" };
colors.Insert(1, "Yellow"); // Inserts "Yellow" at index 1
After this operation, the list will be: ["Red", "Yellow", "Green", "Blue"]
.
5. Access Elements
You can access elements using their index:
Console.WriteLine(colors[0]); // Output: Red
Console.WriteLine(colors[2]); // Output: Green
6. Iterate Through the List
Use a foreach loop to iterate through the list:
foreach (string color in colors)
{
Console.WriteLine(color);
}
Alternatively, use a for loop with indexing:
for (int i = 0; i < colors.Count; i++)
{
Console.WriteLine(colors[i]);
}
7. Remove Elements
You can remove elements in several ways:
- Remove: Removes the first occurrence of a specific element.
- RemoveAt: Removes the element at a specified index.
- RemoveAll: Removes all elements that match a condition.
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
numbers.Remove(30); // Removes the number 30
numbers.RemoveAt(0); // Removes the first element (10)
numbers.RemoveAll(n => n > 40); // Removes all elements greater than 40
8. Count Elements
Use the Count property to get the number of elements in the list:
int count = numbers.Count;
Console.WriteLine($"Number of elements: {count}");
9. Sort and Reverse the List
Sort the list in ascending order:
Reverse the order of elements:
10. Use LINQ with List<T>
LINQ (Language Integrated Query) provides powerful querying capabilities. Here are some examples:
- Filtering with Where:
var filteredNumbers = numbers.Where(n => n > 20);
- Sorting with OrderBy:
var sortedNumbers = numbers.OrderBy(n => n);
- Aggregation with Sum, Average, etc.:
int sum = numbers.Sum();
double average = numbers.Average();
Common Methods and Properties of List<T>
Here’s a quick reference to some of the most commonly used methods and properties:
Methods:
- Add(T item): Adds an item to the end of the list.
- AddRange(IEnumerable<T> collection): Adds multiple items to the list.
- Insert(int index, T item): Inserts an item at a specific index.
- Remove(T item): Removes the first occurrence of an item.
- RemoveAt(int index): Removes the item at a specific index.
- Clear(): Removes all items from the list.
- Contains(T item): Checks if the list contains a specific item.
- IndexOf(T item): Returns the index of the first occurrence of an item.
- Sort(): Sorts the list.
- Reverse(): Reverses the order of elements in the list.
Properties:
- Count: Gets the number of elements in the list.
- Capacity: Gets or sets the total number of elements the list can hold without resizing.
- Item[int index]: Gets or sets the element at a specific index.
Why Use List<T>?
The List<T> class is a go-to choice for managing collections in C# because of its flexibility, performance, and ease of use. Whether you’re building a simple application or a complex system, List<T> provides the tools you need to handle data efficiently.
Conclusion
The List<T> class in C# is a powerful and versatile tool for managing collections. With its dynamic sizing, type safety, and rich set of methods, it simplifies many common programming tasks. By mastering List<T>, you’ll be well-equipped to handle a wide range of scenarios in your C# projects.
Start experimenting with List<T> today, and you’ll quickly see why it’s a favorite among C# developers!