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>

用來建立 IEnumerable<T> 的來源 List<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