您好我正在尝试将所有数据表值合计为一行。但我检索InvalidCastException:
无法转换对象 typeWhereSelectEnumerableIterator
2[System.Linq.IGrouping
2 [System.Object的,的System.Data.DataRow],VB $ AnonymousType_0`4 [System.Object的,System.Double,System.Decimal,System.Decimal]] 键入System.Data.DataTable。
SQL数据类型:
sal_sjuklon money
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result = dataTable.AsEnumerable().GroupBy(
Function(row) row.Item("NAME_AGE")).Select(Function(group) New With {
.Grp = group.Key,
.LON = group.Sum(Function(r) Decimal.Parse(r.Item("LON"))),
.sal_tjformon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon"))),
.sal_sjuklon = group.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon")))
})
Return result
答案 0 :(得分:0)
LINQ语句返回IEnumerable(Of <anonymous_type>)
。这有两个问题。首先,你的函数返回一个DataTable
,你的对象肯定不是。其次,您无法从函数调用中返回匿名类型。
如果要返回选择结果,则必须创建显式类型(类)并返回IEnumerable(Of MyType)
,如下面的代码所示。我强烈建议为Grp
属性设置一个显式类型(如String
?)。
Class GroupNameAgeResult
Public Property Grp As Object
Public Property LON As Decimal
Public Property sal_tjformon As Decimal
Public Property sal_sjuklon As Decimal
End Class
Private Function GroupByName(dataTable As DataTable) As IEnumerable(Of GroupNameAgeResult)
Dim result = dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE")) _
.Select(Function(grp) New GroupNameAgeResult() With
{.Grp = grp.Key,
.LON = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString)),
.sal_tjformon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString)),
.sal_sjuklon = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))})
Return result
End Function
如果要返回DataTable
,可以定义它,循环组并添加一行。之后您可以返回结果。请参阅下面的示例代码。
Private Function GroupByName(dataTable As DataTable) As DataTable
Dim result As New DataTable()
result.Columns.Add("Grp", GetType(Object))
result.Columns.Add("LON", GetType(Decimal))
result.Columns.Add("sal_tjformon", GetType(Decimal))
result.Columns.Add("sal_sjuklon", GetType(Decimal))
For Each grp In dataTable.AsEnumerable().GroupBy(Function(row) row.Item("NAME_AGE"))
Dim row As DataRow = result.NewRow()
row.Item("Grp") = grp.Key
row.Item("LON") = grp.Sum(Function(r) Decimal.Parse(r.Item("LON").ToString))
row.Item("sal_tjformon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_tjformon").ToString))
row.Item("sal_sjuklon") = grp.Sum(Function(r) Decimal.Parse(r.Item("sal_sjuklon").ToString))
result.Rows.Add(row)
Next
Return result
End Function
最后但并非最不重要。我强烈建议你打开&#34; Option strict&#34; (您可以在项目属性中设置此项 - &gt;编译)。您会发现代码中存在更多(可能)错误(即使是此问题中的小函数)。