List<T> Class
Assembly: System.Private.CoreLib (in System.Private.CoreLib.dll)
Overview
Represents a strongly typed list of objects that can be accessed by index. Provides methods for creating, searching, and manipulating lists.
List<T> is a generic collection that provides dynamic resizing and efficient element access. It implements the IList<T> interface, offering a rich set of operations.
Generic Type Parameters
-
T
The type of elements to store in the list.
Inheritance Hierarchy
System.Object
System.Collections.Generic.List<T>
Syntax
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>
Constructors
-
List()
public List()Initializes a new instance of the
List<T>class that is empty, has the default initial capacity, and uses the default equality comparer for the type of elements that the list will store. -
List(Int32)
public List(Int32 capacity)Initializes a new instance of the
List<T>class that is empty and has the specified initial capacity or contains the specified collection of elements and uses the default equality comparer for the type of elements that the list will store.Parameters:capacity: The number of elements that the new list can initially store.
-
List(IEnumerable<T>)
public List(IEnumerable<T> collection)Initializes a new instance of the
List<T>class that contains elements copied from the specified collection and has enough available space to accommodate the number of elements copied.Parameters:collection: The collection whose elements are copied to the new list.
Properties
-
Capacity
public Int32 Capacity { get; set; }Gets or sets the number of elements that the
List<T>can hold.Capacityrepresents the number of elements that theList<T>can currently store. This property can be set to increase or decrease the capacity of the list. If the capacity is decreased below the current number of elements, anArgumentOutOfRangeExceptionis thrown. -
Count
public Int32 Count { get; }Gets the number of elements actually contained in the
List<T>.The
Countproperty reflects the current number of elements in the list. It is always less than or equal toCapacity. -
Item[Int32]
public T Item[Int32 index] { get; set; }Gets or sets the element at the specified index.
This property allows direct access to elements using their zero-based index. Setting the element at a specific index can throw an
ArgumentOutOfRangeExceptionif the index is out of bounds.Parameters:index: The zero-based index of the element to get or set.
Methods
-
Add(T)
public void Add(T item)Adds an object to the end of the
List<T>.If the list has reached its capacity, the capacity is increased to accommodate the new element.
Parameters:item: The object to be added to the end of theList<T>. The value can benullfor reference types.
-
AddRange(IEnumerable<T>)
public void AddRange(IEnumerable<T> collection)Adds the elements of the specified collection to the end of the
List<T>.Parameters:collection: The collection whose elements are to be added to the end of theList<T>.
-
Clear()
public void Clear()Removes all elements from the
List<T>.After clearing the list, the
Countproperty will be zero. -
Contains(T)
public bool Contains(T item)Determines whether an element is in the
List<T>.This method performs a linear search to find the element. If the type
Tis a reference type, the method checks for equality using the default equality comparer.Parameters:item: The object to locate in theList<T>. The value can benullfor reference types.
Returns:trueifitemis found in theList<T>; otherwise,false. -
Exists(Predicate<T>)
public bool Exists(Predicate<T> match)Determines whether any element in the
List<T>matches the specified predicate.Parameters:match: ThePredicate<T>delegate that defines the conditions of the elements to search for.
Returns:trueif the list contains one or more elements that match the conditions specified by the predicate; otherwise,false. -
Find(Predicate<T>)
public T Find(Predicate<T> match)Searches for an element that matches the conditions defined by the specified predicate and returns the first occurrence in the entire
List<T>.Parameters:match: ThePredicate<T>delegate that defines the conditions of the element to search for.
Returns:The first element that matches the specified predicate, or the default value of
Tif not found. -
FindAll(Predicate<T>)
public List<T> FindAll(Predicate<T> match)Implements the remainder of the search. Uses the specified
Predicate<T>to filter the list.Parameters:match: ThePredicate<T>delegate that defines the conditions of the elements to search for.
Returns:A
List<T>containing all the elements that match the conditions defined by the specified predicate. An emptyList<T>if no elements match. -
IndexOf(T)
public Int32 IndexOf(T item)Searches for the specified object and returns the zero-based index of the first occurrence within the entire
List<T>.Parameters:item: The object to locate in theList<T>. The value can benullfor reference types.
Returns:The zero-based index of the first occurrence of
itemwithin the entireList<T>, if found; otherwise, -1. -
Insert(Int32, T)
public void Insert(Int32 index, T item)Inserts an element into the
List<T>at the specified index.Elements from the insertion point onwards are shifted to the right.
Parameters:index: The zero-based index at whichitemshould be inserted.item: The object to insert.
-
Remove(T)
public bool Remove(T item)Removes the first occurrence of a specific object from the
List<T>.If the object is found, it is removed, and subsequent elements are shifted to the left.
Parameters:item: The object to remove from theList<T>. The value can benullfor reference types.
Returns:trueifitemwas successfully removed from theList<T>; otherwise,false. This method also returnsfalseifitemis not found in the originalList<T>. -
RemoveAll(Predicate<T>)
public Int32 RemoveAll(Predicate<T> match)Removes all the elements that match the conditions defined by the specified predicate.
Parameters:match: ThePredicate<T>delegate that defines the conditions of the elements to remove.
Returns:The number of elements removed from the
List<T>. -
RemoveAt(Int32)
public void RemoveAt(Int32 index)Removes the element at the specified index of the
List<T>.Elements from the removal point onwards are shifted to the left.
Parameters:index: The zero-based index of the element to remove.
-
Sort()
public void Sort()Sorts the elements in the entire
List<T>using the default comparer.This method uses an implementation of the quicksort algorithm.
-
Sort(Comparison<T>)
public void Sort(Comparison<T> comparison)Sorts the elements in the entire
List<T>using the specifiedComparison<T>delegate.Parameters:comparison: TheComparison<T>delegate used to compare elements.
-
ToArray()
public T[] ToArray()Converts the elements in the current
List<T>to an array.This method creates a new array with the same elements as the list.
Returns:A new array containing the elements of the
List<T>. -
TrimExcess()
public void TrimExcess()Sets the capacity to the actual number of elements in the
List<T>.This method is useful for minimizing memory usage when the list has grown significantly and then been reduced in size.
Example
Creating and manipulating a List of strings
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new list of strings.
List<string> stringList = new List<string>();
// Add elements to the list.
stringList.Add("apple");
stringList.Add("banana");
stringList.Add("cherry");
Console.WriteLine($"Initial list count: {stringList.Count}"); // Output: Initial list count: 3
// Insert an element at a specific index.
stringList.Insert(1, "blueberry");
// Access and modify an element.
stringList[0] = "apricot";
// Iterate through the list.
Console.WriteLine("\nList contents:");
foreach (string fruit in stringList)
{
Console.WriteLine(fruit);
}
// Output:
// List contents:
// apricot
// blueberry
// banana
// cherry
// Remove an element.
stringList.Remove("banana");
Console.WriteLine($"\nList count after removing 'banana': {stringList.Count}"); // Output: List count after removing 'banana': 3
// Check if an element exists.
if (stringList.Contains("cherry"))
{
Console.WriteLine("List contains 'cherry'.");
}
// Convert the list to an array.
string[] stringArray = stringList.ToArray();
Console.WriteLine($"\nArray count: {stringArray.Length}"); // Output: Array count: 3
}
}