轉換資料類型 (Visual Basic)

轉換方法會變更輸入物件的類型。

LINQ 查詢中的轉換作業可用於各種應用程式。 下列是部份範例:

方法

下表列出執行資料型別轉換的標準查詢運算子方法。

此表格中名稱開頭為"As" 的轉換方法會變更來源集合的靜態類型,而不是列舉它。 名稱開頭為 "To" 的方法會列舉來源集合,並將項目放入對應的集合類型。

方法名稱 描述 Visual Basic 查詢運算式語法 相關資訊
AsEnumerable 傳回 IEnumerable<T> 類型的輸入。 不適用。 Enumerable.AsEnumerable
AsQueryable 將 (泛型) IEnumerable 轉換成 (泛型) IQueryable 不適用。 Queryable.AsQueryable
Cast 將集合的項目轉型為指定的類型。 From … As … Enumerable.Cast

Queryable.Cast
OfType 根據可轉型為所指定類型的能力來篩選值。 不適用。 Enumerable.OfType

Queryable.OfType
ToArray 將集合轉換為陣列。 這個方法會強制執行查詢。 不適用。 Enumerable.ToArray
ToDictionary 根據索引鍵選取器函式,將項目放入 Dictionary<TKey,TValue>。 這個方法會強制執行查詢。 不適用。 Enumerable.ToDictionary
ToList 將集合轉換成 List<T>。 這個方法會強制執行查詢。 不適用。 Enumerable.ToList
ToLookup 根據索引鍵選取器函式,將項目放入 Lookup<TKey,TElement> (一對多字典)。 這個方法會強制執行查詢。 不適用。 Enumerable.ToLookup

查詢運算式語法範例

下列程式碼範例會先使用 From As 子句將類型轉換為子類型,再存取只能在子類型中使用的成員。

Class Plant
    Public Property Name As String
End Class

Class CarnivorousPlant
    Inherits Plant
    Public Property TrapType As String
End Class

Sub Cast()

    Dim plants() As Plant = {
        New CarnivorousPlant With {.Name = "Venus Fly Trap", .TrapType = "Snap Trap"},
        New CarnivorousPlant With {.Name = "Pitcher Plant", .TrapType = "Pitfall Trap"},
        New CarnivorousPlant With {.Name = "Sundew", .TrapType = "Flypaper Trap"},
        New CarnivorousPlant With {.Name = "Waterwheel Plant", .TrapType = "Snap Trap"}}

    Dim query = From plant As CarnivorousPlant In plants
                Where plant.TrapType = "Snap Trap"
                Select plant

    Dim sb As New System.Text.StringBuilder()
    For Each plant In query
        sb.AppendLine(plant.Name)
    Next

    ' Display the results.
    MsgBox(sb.ToString())

    ' This code produces the following output:

    ' Venus Fly Trap
    ' Waterwheel Plant

End Sub

另請參閱