LINQ轉換操作


運算子改變輸入物件的型別,並在多種不同的應用範圍中使用。

操作 描述 C#查詢表示式語法 VB查詢表示式語法
AsEnumerable 返回輸入型別為IEnumerable<T> 不適用 不適用
AsQueryable (通用)IEnumerable的被轉換為(通用)IQueryable 不適用 不適用
Cast 執行一個集合的元素的轉換到一個指定型別 使用顯式型別範圍變數。例如:從str在字串String中 From … As …
OfType 在它們的基礎上過濾值,這取決於它們的能力,以被轉換為特定型別 不適用 不適用
ToArray 強制執行查詢並執行轉換集合到一個陣列 不適用 不適用
ToDictionary 在一鍵選擇功能的基礎上設定元素的LINQ查詢到字典<TKEY,TValue>中和執行 不適用 不適用
ToList 強制執行查詢由一個集合轉換為 List<T> 不適用 不適用
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.