Skip to content

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

C# LINQ —— 一组扩展方法,用于以声明式语法查询 IEnumerable<T> 序列。

1 class · 7 methods

Enumerable

7 methods

提供一组静态方法,用于查询实现 IEnumerable<T> 的对象。

List<T>.Add(T item)

基于谓词筛选值序列。

Parameters

NameTypeDescription
sourceT要筛选的序列。

Returns

void

Example

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

将序列中的每个元素投影到新形式。

Returns

int

Example

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

根据键按升序对序列中的元素进行排序。

Parameters

NameTypeDescription
sourceT要排序的序列。

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

计算 int 值序列的总和。

Parameters

NameTypeDescription
sourceT要求总和的序列。

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()

返回序列中元素的数量。

Returns

void

Example

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

返回序列的第一个元素。如果序列为空则抛出异常。

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

使用默认相等比较器返回序列中的不同元素。

Parameters

NameTypeDescription
sourcePredicate<T>要从中移除重复项的序列。

Returns

T

Example

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