This article will break down everything you need to know, complete with examples to help you get started.
What Is a List<T>?
In simple terms, a List<T> is a resizable array in C#. Unlike arrays, which have a fixed size after creation, a List<T> expands or shrinks as needed. The <T> denotes that it is a generic type, meaning you can specify the data type it holds.
Here are some key benefits of using List<T>:
- Resizable: No need to predefine its capacity.
- Strongly-Typed: Ensures the type of data it holds matches the specified type of
<T>. - Rich Functionality: Comes with built-in methods like
Add,Remove,Sort, and more.
For an overview of basic C# structures, check out this guide to C# Variables.
Getting Started: How to Use List<T>
Creating a List<T>
To create a List<T>, simply declare it and specify the type it will hold. Here’s a basic example:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Initialize a list of integers
List<int> numbers = new List<int>();
// Add values to the list
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Display the list
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
Explanation:
- You use
new List<int>()to initialize the list. - The
Addmethod inserts items into the list. - The
foreachloop iterates through and prints each item.
Accessing and Modifying Items
You can access elements using an index, just like an array. Here's an example:
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };
Console.WriteLine(names[0]); // Outputs: Alice
names[1] = "David"; // Replaces "Bob" with "David"
Console.WriteLine(names[1]); // Outputs: David
Key Points:
- Indexes start at
0. - You can directly replace an item by specifying its index.
Common Methods
Here are some useful methods you’ll frequently use:
Add: Adds an element at the end of the list.Insert: Adds an element at a specific index.RemoveandRemoveAt: Deletes items.Count: Returns the number of elements in the list.
Let’s see a practical example:
List<string> cities = new List<string>();
// Add cities
cities.Add("New York");
cities.Add("Los Angeles");
cities.Add("Chicago");
// Insert a city at position 1
cities.Insert(1, "Houston");
// Remove a city
cities.Remove("Los Angeles");
// Display cities
foreach (string city in cities)
{
Console.WriteLine(city);
}
Output:
New York
Houston
Chicago
For related sorting techniques, refer to the article on Sorting with Lambdas.
Advanced Features of List<T>
Sorting with .Sort()
Sorting becomes simple with the Sort method:
List<int> numbers = new List<int>() { 5, 1, 4, 2, 3 };
numbers.Sort();
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Output:
1
2
3
4
5
Filtering with .FindAll()
Use FindAll to filter items based on a condition. For instance:
List<int> numbers = new List<int>() { 5, 1, 4, 2, 3 };
List<int> evens = numbers.FindAll(x => x % 2 == 0);
foreach (int even in evens)
{
Console.WriteLine(even);
}
Output:
4
2
Checking Items with .Contains()
You can check if an item exists with Contains:
List<string> fruits = new List<string>() { "Apple", "Banana", "Cherry" };
if (fruits.Contains("Banana"))
{
Console.WriteLine("Banana is in the list!");
}
Performance Considerations
While List<T> is flexible, keeping performance in mind is key. For instance:
- Adding many items at once? Predefine the capacity with the
Capacityproperty. - For highly frequent operations, consider alternatives like
LinkedList<T>orHashSet<T>.
Explore the use of access scopes and modifiers in this supplementary post about C# access modifiers.
Conclusion
The List<T> in C# unlocks endless possibilities for managing collections dynamically. Its rich functionality ensures efficiency and simplicity for novice and experienced developers alike. Practice working with various methods to master its potential.
For more on related topics, check out this guide to working with C# files. Experiment with these examples and see how a List<T> can simplify your next project.