Skip to content

C# System.Collections.Generic.List<T> API

C# List<T> — a strongly-typed, dynamically-resizable list backed by an internal array.

1 class · 7 methods

List<T>

7 methods

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

List<T>.Add(T item)

Adds an object to the end of the List<T>.

Parameters

NameTypeDescription
itemTObject to be added to the end of the list.

Returns

void

Example

csharp
var list = new List<int>();
list.Add(1);
list.Add(2);
// list == [1, 2]
List<T>.Count -> int

Gets the number of elements contained in the List<T>.

Returns

int

Example

csharp
var list = new List<int> { 1, 2, 3 };
int n = list.Count;  // 3
List<T>.Remove(T item) -> bool

Removes the first occurrence of a specific object. Returns true if item was successfully removed.

Parameters

NameTypeDescription
itemTObject to remove from the list.

Returns

bool

Example

csharp
var list = new List<int> { 1, 2, 3 };
bool ok = list.Remove(2);  // true
// list == [1, 3]
bool ok2 = list.Remove(9); // false
List<T>.Contains(T item) -> bool

Determines whether an element is in the List<T>.

Parameters

NameTypeDescription
itemTObject to locate in the list.

Returns

bool

Example

csharp
var list = new List<int> { 1, 2, 3 };
bool has = list.Contains(2);  // true
bool no = list.Contains(9);   // false
List<T>.Sort()

Sorts the elements in the entire List<T> using the default comparer.

Returns

void

Example

csharp
var list = new List<int> { 3, 1, 2 };
list.Sort();
// list == [1, 2, 3]
List<T>.ToArray() -> T[]

Copies the elements of the List<T> to a new array.

Returns

T[]

Example

csharp
var list = new List<int> { 1, 2, 3 };
int[] arr = list.ToArray();  // [1, 2, 3]
List<T>.Find(Predicate<T> match) -> T

Searches for an element that matches the conditions defined by the specified predicate.

Parameters

NameTypeDescription
matchPredicate<T>Predicate delegate that defines the conditions.

Returns

T

Example

csharp
var list = new List<int> { 1, 2, 3, 4 };
int firstEven = list.Find(x => x % 2 == 0);  // 2