Enumerable.ToList<TSource>(IEnumerable<TSource>) 方法

定义

IEnumerable<T> 创建一个 List<T>

C#
public static System.Collections.Generic.List<TSource> ToList<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

类型参数

TSource

source 的元素类型。

参数

source
IEnumerable<TSource>

要从其创建 List<T>IEnumerable<T>

返回

List<TSource>

一个包含输入序列中的元素的 List<T>

例外

sourcenull

示例

下面的代码示例演示如何使用 ToList 强制立即查询计算并返回 List<T> 包含查询结果的 。

C#
string[] fruits = { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };

List<int> lengths = fruits.Select(fruit => fruit.Length).ToList();

foreach (int length in lengths)
{
    Console.WriteLine(length);
}

/*
 This code produces the following output:

 5
 12
 6
 5
 6
 9
 5
 10
*/

注解

方法 ToList<TSource>(IEnumerable<TSource>) 强制立即进行查询计算,并返回包含 List<T> 查询结果的 。 可以将此方法追加到查询中,以获取查询结果的缓存副本。

ToArray 具有类似的行为,但返回数组而不是 List<T>

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0