List<T> Class
Represents a strongly typed list of objects that can be accessed by index. Provides methods for searching, sorting, and manipulating lists.
Namespace
System.Collections.Generic
Inheritance
Object
> IList<T>
> ICollection<T>
> IEnumerable<T>
> IEnumerable
Introduction
The List<T>
generic collection is a versatile and efficient data structure in the .NET Framework. It acts as a dynamic array, allowing you to add, remove, and access elements with ease. Its generic nature ensures type safety, preventing runtime errors related to type mismatches.
Key Features
- Type Safety: Enforces the type of elements stored, reducing casting errors.
- Dynamic Sizing: Automatically resizes as elements are added or removed.
- Indexed Access: Elements can be accessed directly using their zero-based index.
- Rich Functionality: Offers numerous methods for common list operations like adding, inserting, removing, searching, sorting, and copying.
- LINQ Support: Fully compatible with Language Integrated Query (LINQ) for powerful data querying.
Creating and Initializing a List
You can create a new List<T>
by specifying the type of elements it will hold.
using System;
using System.Collections.Generic;
// Create a list of strings
List<string> names = new List<string>();
// Create a list with an initial capacity
List<int> numbers = new List<int>(10); // Pre-allocates space for 10 elements
// Create a list and initialize it with elements
List<double> values = new List<double>() { 1.1, 2.2, 3.3 };
Common Operations
Adding Elements
Use the Add()
method to append an element to the end of the list, or Insert()
to add at a specific index.
List<string> fruits = new List<string>();
fruits.Add("Apple"); // ["Apple"]
fruits.Add("Banana"); // ["Apple", "Banana"]
fruits.Insert(1, "Orange"); // ["Apple", "Orange", "Banana"]
Accessing Elements
Access elements using their index.
string firstFruit = fruits[0]; // "Apple"
string secondFruit = fruits[1]; // "Orange"
Removing Elements
Use Remove()
to remove the first occurrence of a specific element, RemoveAt()
to remove by index, or RemoveRange()
to remove a section.
fruits.Remove("Orange"); // ["Apple", "Banana"]
fruits.RemoveAt(0); // ["Banana"]
fruits.Add("Grape");
fruits.Add("Mango");
fruits.RemoveRange(0, 2); // Removes "Banana" and "Grape" - list is now ["Mango"]
Searching
Use Contains()
to check for existence, or IndexOf()
/ LastIndexOf()
to find the index of an element.
bool hasApple = fruits.Contains("Apple"); // False (if already removed)
int indexOfGrape = fruits.IndexOf("Grape"); // -1 if not found
Sorting
The Sort()
method sorts the elements in ascending order. You can also provide a custom comparer.
List<int> scores = new List<int>() { 85, 92, 78, 92, 88 };
scores.Sort(); // [78, 85, 88, 92, 92]
Count and Capacity
Count
: The number of elements currently in the list.Capacity
: The number of elements the list can hold before resizing.
int fruitCount = fruits.Count; // Current number of fruits
int numberCapacity = numbers.Capacity; // Current capacity of the numbers list
API Reference
Method / Property | Description |
---|---|
Add(T item) |
Appends an item to the end of the List<T>. |
AddRange(IEnumerable<T> collection) |
Adds the elements of the specified collection to the end of the List<T>. |
Clear() |
Removes all elements from the List<T>. |
Contains(T item) |
Determines whether an element is in the List<T>. |
Exists(Predicate<T> match) |
Determines whether any element in the List<T> matches the specified predicate. |
Find(Predicate<T> match) |
Searches for an element that matches the specified predicate and returns the zero-based index of the first occurrence within the entire List<T>. |
FindAll(Predicate<T> match) |
Implements theIList.Contains(Object) method. |
ForEach(Action<T> action) |
Performs the specified action on each element of the List<T>. |
GetRange(int index, int count) |
Returns a shallow, shallow copy of a portion of the List<T>. |
IndexOf(T item) |
Searches for the specified object and returns the zero-based index of the first occurrence within the entire List<T>. |
Insert(int index, T item) |
Inserts an item at the specified index of the List<T>. |
Remove(T item) |
Removes the first occurrence of a specific object from the List<T>. |
RemoveAt(int index) |
Removes the element at the specified index of the List<T>. |
RemoveRange(int index, int count) |
Removes the specified number of elements from the List<T> starting at the specified index. |
Reverse() |
Reverses the order of the elements in the entire List<T>. |
Sort() |
Sorts the elements in the entire List<T> using the default comparer. |
ToArray() |
Copies the entire List<T> to a new array. |
TrimExcess() |
Sets the capacity to the actual number of elements in the List<T>, if that number is less than 90 percent of the current capacity. |
Count |
Gets the number of elements actually contained in the List<T>. |
Capacity |
Gets or sets the number of elements that the List<T> can contain. |
List<T>
is generally preferred over the older non-generic ArrayList
because it is type-safe and more performant.
For more advanced scenarios, consider using LINQ extension methods on List<T>
for querying and manipulation.