在 vb.net 中使用 Linq 对 DataTable 执行聚合
给定一个数据表,我希望输出一个 IEnumerable 类型(字典(T)将是完美的,否则数据表是可以接受的),它提供数据表中数据的聚合。
在 SQL 中,我会这样编写查询:
select groupByColumn, sum(someNumber) from myTable group by groupByColumn
在 VB.NET 中,我最接近这个(使用信息 此处)是:
' dt is a datatable containing two columns, referred to by index in p below
Dim q = From p In dt Group p By p(0) Into Sum(p(1)) Select p(0), SumOfNumber = Sum
但是我收到错误:“范围变量名称只能从简单的推断或不带参数的限定名称。” 在 p(0) 元素上。
因此我的问题如下:
- 我该如何解决这个错误?
- 如何将结果 (q) 处理为 IEnumerable 类型?
生活并没有因为我在不熟悉的 vb.net 中使用 Linq 而变得更容易。很多例子都是用 C# 编写的,但即使是用 C# 编写,我也没有真正遇到过任何合适的例子。
Given a datatable, I wish to output an IEnumerable type (dictionary(of T) would be perfect, otherwise a datatable would be acceptable) that provides an aggregation of the data within the datatable.
In SQL I would write the query as such:
select groupByColumn, sum(someNumber) from myTable group by groupByColumn
In VB.NET the closest I have got to this (achieved using information here) is:
' dt is a datatable containing two columns, referred to by index in p below
Dim q = From p In dt Group p By p(0) Into Sum(p(1)) Select p(0), SumOfNumber = Sum
However I receive error: "Range variable name can be inferred only from a simple or qualified name with no arguments." on the p(0) element.
Therefore my question is as follows:
- How can I resolve this error?
- How do I process the result (q) as an IEnumerable type?
Life isn't made any easier because I'm using Linq in unfamiliar vb.net. Many examples are in C#, but I haven't really come across anything suitable even in C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已解决:我必须为返回的列添加别名。
另请注意,我必须对要求和的值进行转换,因为动态返回的数据表没有指定列类型。
提示此处 因为 vb.net 非常有帮助,为我们提供了与 C# 不同的错误消息“无效的匿名类型成员声明符。匿名类型成员必须使用成员赋值、简单名称或成员访问权限进行声明。”
完整性,结果处理如下:
Resolved: I had to alias the columns returned.
Also note that I had to do a conversion on the value that I was summing because being a dynamically returned datatable didn't have the column type specified.
Hint found here because vb.net oh so helpfully gives us a different error message to C#'s "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access."
For completeness, results are processed as below: