转换数据类型
更新:2007 年 11 月
转换方法更改输入对象的类型。
LINQ 查询中的转换运算可用于各种应用程序。下面是一些示例:
Enumerable.AsEnumerable<TSource> 方法可用于隐藏类型的标准查询运算符的自定义实现。
Enumerable.OfType<TResult> 方法可用于启用非参数化集合以进行 LINQ 查询。
Enumerable.ToArray<TSource>、Enumerable.ToDictionary、Enumerable.ToList<TSource> 和 Enumerable.ToLookup 方法可用于强制立即执行查询,而非推迟到枚举查询时。
方法
下表列出了执行数据类型转换的标准查询运算符方法。
此表中名称以“As”开头的转换方法可更改源集合的静态类型但不枚举此源集合。名称以“To”开头的方法可枚举源集合并将项放入相应的集合类型。
方法名 |
说明 |
C# 查询表达式语法 |
Visual Basic 查询表达式语法 |
更多信息 |
---|---|---|---|---|
AsEnumerable |
返回类型化为 IEnumerable<T> 的输入。 |
不适用。 |
不适用。 |
|
AsQueryable |
将(泛型)IEnumerable 转换为(泛型)IQueryable。 |
不适用。 |
不适用。 |
|
Cast |
将集合的元素强制转换为指定类型。 |
使用显式类型化的范围变量。例如: from string str in words |
From … As … |
|
OfType |
根据值强制转换为指定类型的能力筛选值。 |
不适用。 |
不适用。 |
|
ToArray |
将集合转换为数组。此方法强制执行查询。 |
不适用。 |
不适用。 |
|
ToDictionary |
根据键选择器函数将元素放入 Dictionary<TKey, TValue> 中。此方法强制执行查询。 |
不适用。 |
不适用。 |
|
ToList |
将集合转换为 List<T>。此方法强制执行查询。 |
不适用。 |
不适用。 |
|
ToLookup |
根据键选择器函数将元素放入 Lookup<TKey, TElement>(一对多字典)中。此方法强制执行查询。 |
不适用。 |
不适用。 |
查询表达式语法示例
下面的代码示例使用显式类型化的范围变量(在 C# 中)或 From As 子句(在 Visual Basic 中)将类型强制转换为子类型,然后才访问只具有此子类型的成员。
Class Plant
Public Name As String
End Class
Class CarnivorousPlant
Inherits Plant
Public 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
class Plant
{
public string Name { get; set; }
}
class CarnivorousPlant : Plant
{
public string TrapType { get; set; }
}
static void Cast()
{
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 (Plant plant in query)
Console.WriteLine(plant.Name);
/* This code produces the following output:
Venus Fly Trap
Waterwheel Plant
*/
}
有关如何转换数据类型的更多信息
Topic | Location |
---|---|
如何:使用 LINQ 查询 ArrayList | 语言集成查询 (LINQ) |
如何:使用 LINQ 查询 ArrayList | dv_Linq |
如何:使用 LINQ 查询 ArrayList | dv_Linq |