LINQ轉換操作

運算符改變輸入對象的類型,並在多種不同的應用範圍中使用。

操作

描述

C#查詢表達式語法

VB查詢表達式語法

AsEnumerable

返回輸入類型爲IEnumerable

不適用

不適用

AsQueryable

(通用)IEnumerable的被轉換爲(通用)IQueryable

不適用

不適用

Cast

執行一個集合的元素的轉換到一個指定類型

使用顯式類型範圍變量。例如:從str在字符串String中

From … As …

OfType

在它們的基礎上過濾值,這取決於它們的能力,以被轉換爲特定類型

不適用

不適用

ToArray

強制執行查詢並執行轉換集合到一個數組

不適用

不適用

ToDictionary

在一鍵選擇功能的基礎上設置元素的LINQ查詢到字典<TKEY,TValue>中和執行

不適用

不適用

ToList

強制執行查詢由一個集合轉換爲 List

不適用

不適用

ToLookup

強制執行查詢,並把元素融入一個Lookup<TKEY,TElement>鍵選擇器函數

不適用

不適用

轉換例子- 查詢表達式

C# 代碼示例

using System; using System.Linq; namespace Operators { class Cast { static void Main(string[] args) { Plant[] plants = new Plant[] {new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" }, new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" }, new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" }, new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }}; var query = from CarnivorousPlant cPlant in plants where cPlant.TrapType == "Snap Trap" select cPlant; foreach (var e in query) { Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } class Plant { public string Name { get; set; } } class CarnivorousPlant : Plant { public string TrapType { get; set; } } }

VB 代碼示例

Module Module1 Sub Main() 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 list = From cPlant As CarnivorousPlant In plants Where cPlant.TrapType = "Snap Trap" Select cPlant For Each e In list Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Class Plant Public Property Name As String End Class Class CarnivorousPlant Inherits Plant Public Property TrapType As String End Class End Module

當在C#或VB上面的代碼被編譯和執行時,它產生了以下結果:

Name = Venus Fly Trap, TrapType = Snap Trap
Name = Waterwheel Plant, TrapType = Snap Trap

Press any key to continue.