运算符改变输入对象的类型,并在多种不同的应用范围中使用。
操作 | 描述 | 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.