LINQ中的转换



这些运算符更改输入对象的类型,并用于各种应用。

运算符 说明 C# 查询表达式语法 VB 查询表达式语法
AsEnumerable 将输入类型化为 IEnumerable<T> 不适用 不适用
AsQueryable 将(泛型)IEnumerable 转换为(泛型)IQueryable 不适用 不适用
Cast 执行将集合元素强制转换为指定类型的操作 使用显式类型的范围变量。例如:from string str in words From … As …
OfType 根据值过滤值,具体取决于它们被强制转换为特定类型的功能 不适用 不适用
ToArray 强制执行查询并转换集合为数组 不适用 不适用
ToDictionary 在 Dictionary<TKey, TValue> 中根据键选择器函数设置元素,并强制执行 LINQ 查询 不适用 不适用
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.
linq_query_operators.htm
广告