转换方法更改输入对象的类型。
LINQ 查询中的转换作在各种应用程序中非常有用。 下面是一些示例:
该方法 Enumerable.AsEnumerable 可用于隐藏标准查询运算符的类型自定义实现。
该方法 Enumerable.OfType 可用于为 LINQ 查询启用非参数化集合。
Enumerable.ToArray、Enumerable.ToDictionary、Enumerable.ToList和Enumerable.ToLookup方法可以用于强制立即执行查询,而不是推迟执行直到查询被枚举。
方法
下表列出了执行数据类型转换的标准查询运算符方法。
此表中名称以“As”开头的转换方法更改源集合的静态类型,但不枚举它。 名称以“To”开头的方法枚举源集合,并将项放入相应的集合类型。
方法名 | DESCRIPTION | Visual Basic 查询表达式语法 | 详细信息 |
---|---|---|---|
AsEnumerable | 返回类型化为 IEnumerable<T> 的输入。 | 不適用。 | Enumerable.AsEnumerable |
AsQueryable | 将 (generic) IEnumerable 转换为 (generic) IQueryable。 | 不適用。 | Queryable.AsQueryable |
演员阵容 | 将集合的元素强制转换为指定类型。 | From … As … |
Enumerable.Cast Queryable.Cast |
OfType | 根据其转换为指定类型的能力筛选值。 | 不適用。 | Enumerable.OfType Queryable.OfType |
ToArray | 将集合转换为数组。 此方法强制执行查询。 | 不適用。 | Enumerable.ToArray |
ToDictionary | 根据键选择器函数将元素放入 Dictionary<TKey,TValue>。 此方法强制执行查询。 | 不適用。 | Enumerable.ToDictionary |
ToList | 将集合转换为 List<T>. 此方法强制执行查询。 | 不適用。 | Enumerable.ToList |
ToLookup | 根据键选择器函数将元素放入 Lookup<TKey,TElement>(一对多字典)。 此方法强制执行查询。 | 不適用。 | Enumerable.ToLookup |
查询表达式语法示例
下面的代码示例使用 From As
子句将类型转换为子类型,然后才访问仅在此子类型上可用的成员。
Class Plant
Public Property Name As String
End Class
Class CarnivorousPlant
Inherits Plant
Public Property TrapType As String
End Class
Sub Cast()
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 query = From plant As CarnivorousPlant In plants
Where plant.TrapType = "Snap Trap"
Select plant
Dim sb As New System.Text.StringBuilder()
For Each plant In query
sb.AppendLine(plant.Name)
Next
' Display the results.
MsgBox(sb.ToString())
' This code produces the following output:
' Venus Fly Trap
' Waterwheel Plant
End Sub