VB.Net中如何遍历匿名类型的IEnumerable集合?
解决LINQ匿名类型集合遍历的类型转换错误
问题场景
从SQL Server获取DataTable数据,按VendorID分组并拼接字段多值的代码运行正常:
Dim dt As DataTable = GetVendorData() Dim results = From p In dt.AsEnumerable() Group p By VendorID = p.Field(Of String)("VenID") Into g = Group Select New With { Key .VendorID = VendorID, Key .FundNumber = String.Join(";", From i In g Select i.Field(Of String)("FundNumber")), Key .Statefund = String.Join(";", From i In g Select i.Field(Of String)("Statefund")), Key .State = String.Join(";", From i In g Select i.Field(Of String)("State")) }
但尝试用如下方式遍历时报错:
For Each result As DataRow In results Dim x As String = result.Field(Of String)("FundNumber")) Next
错误信息:
System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'VB$AnonymousType_1`4[System.String,System.String,System.String,System.String]' to type 'System.Data.DataRow'
解决方法
错误核心是results是匿名类型的IEnumerable集合,而非DataRow集合,不能用DataRow类型强制接收。正确遍历方式有两种:
方式1:使用类型推断(推荐)
让VB自动推断匿名类型,直接通过属性名访问字段值:
For Each result In results Dim x As String = result.FundNumber ' 可直接访问其他定义的属性 Dim vendorId As String = result.VendorID Dim stateFund As String = result.Statefund Dim state As String = result.State Next
方式2:用Object类型接收(不推荐,无编译时类型检查)
若必须指定类型,用Object接收后直接访问属性(VB支持后期绑定):
For Each result As Object In results Dim x As String = result.FundNumber Next
补充说明
LINQ的Select New With {...}生成的是匿名类型实例,每个实例包含你定义的VendorID、FundNumber等强类型属性,直接通过.访问即可,无需使用DataRow专属的Field方法。
内容的提问来源于stack exchange,提问作者Massey
相关产品推荐
相关产品推荐

