LINQ 中的转换
运算符可更改输入对象的类型,并可用于各种应用程序。
运算符 | 描述 | C# 查询表达式语法 | VB 查询表达式语法 |
---|---|---|---|
AsEnumerable | 返回类型为 IEnumerable<T> 的输入 | 不适用 | 不适用 |
AsQueryable | A (通用) IEnumerable 转换为 (通用) IQueryable | 不适用 | 不适用 |
转换 | 将集合元素转换为指定类型 | 使用明确类型的范围变量。例如: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(" Press 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.