List<T>
7 methodsRepresents 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
| Name | Type | Description |
|---|---|---|
| item | T | Object 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 -> intGets 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; // 3List<T>.Remove(T item) -> boolRemoves the first occurrence of a specific object. Returns true if item was successfully removed.
Parameters
| Name | Type | Description |
|---|---|---|
| item | T | Object 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); // falseList<T>.Contains(T item) -> boolDetermines whether an element is in the List<T>.
Parameters
| Name | Type | Description |
|---|---|---|
| item | T | Object 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); // falseList<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) -> TSearches for an element that matches the conditions defined by the specified predicate.
Parameters
| Name | Type | Description |
|---|---|---|
| match | Predicate<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