Enumerable.ToList(TSource) 方法

Enumerable.ToList(TSource) 方法

 

 

IEnumerable(TSource) 創建一個 List(TSource)

命名空間:   System.Linq
程序集:  System.Core(在 System.Core.dll 中)

異常條件
ArgumentNullException

sourcenullNothingnullptrnull 引用(在 Visual Basic 中爲 Nothing

ToList(TSource)(IEnumerable(TSource) 方法強制進行直接查詢計算,並返回一個包含查詢值的 (T) 。可將此方法追加到您的查詢,以獲得查詢結果的緩存副本。

ToArray(TSource)具有類似行爲,但它返回一個數組,而非一個 List(T)

下面的代碼示例演示如何使用 ToList(TSource) 強制進行直接查詢計算並返回一個包含查詢結果的 List(T)

Visual Basic
' Create an array of strings.
Dim fruits() As String = _
    {"apple", "passionfruit", "banana", "mango", _
     "orange", "blueberry", "grape", "strawberry"}

' Project the length of each string and 
' put the length values into a List object.
Dim lengths As List(Of Integer) = _
    fruits _
    .Select(Function(fruit) fruit.Length) _
    .ToList()

' Display the results.
Dim output As New System.Text.StringBuilder
For Each length As Integer In lengths
    output.AppendLine(length)
Next
MsgBox(output.ToString())

' This code produces the following output:
'
' 5
' 12
' 6
' 5
' 6
' 9
' 5
' 10

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
*/
Visual Basic(聲明)
<ExtensionAttribute> _
Public Shared Function ToList(Of TSource) ( _
    source As IEnumerable(Of TSource) _
) As List(Of TSource)
Visual Basic (用法)
Dim source As IEnumerable(Of TSource)
Dim returnValue As List(Of TSource)

returnValue = source.ToList()
C#
public static List<TSource> ToList<TSource>(
    this IEnumerable<TSource> source
)
Visual C++
[ExtensionAttribute]
public:
generic<typename TSource>
static List<TSource>^ ToList(
    IEnumerable<TSource>^ source
)
J#
J# 支持使用泛型 API,但是不支持新泛型 API 的聲明。
JScript
JScript 不支持泛型類型或方法。

類型參數

TSource

source 中的元素的類型。

參數

source
類型:System.Collections.Generic..::.IEnumerable (TSource)

要從其創建 List(T) IEnumerable(T)

返回值

類型:System.Collections.Generic..::.List (TSource)

一個包含輸入序列中元素的 List(T)

使用說明

在 Visual Basic 和 C# 中,可以在 IEnumerable(TSource)類型的任何對象上將此方法作爲實例方法來調用。當使用實例方法語法調用此方法時,請省略第一個參數。有關更多信息,請參見 擴展方法 (Visual Basic) 擴展方法(C# 編程指南)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章