vb.net 数据表上的 GroupBy 和 Sum

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17270081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:01:09  来源:igfitidea点击:

GroupBy and Sum on a DataTable

.netvb.netlinqgroup-bysum

提问by Ramesh Durai

I am using LINQ in VB on a datatable to filter my results.

我在 VB 中的数据表上使用 LINQ 来过滤我的结果。

m_oDataTable.Columns.Add("Name1", GetType(String))
m_oDataTable.Columns.Add("Name2", GetType(String))
m_oDataTable.Columns.Add("Time", GetType(Double))

I am trying to filter the datatable by Name1or Name2based on user selection.

我正在尝试通过Name1Name2基于用户选择过滤数据表。

groupBy = "Name1" 
'groupBy = "Name2"

I grouped my data but I was unable to Sumthe desired field.

我对数据进行了分组,但无法找到Sum所需的字段。

Dim test =  From tab In m_oDataTable.AsEnumerable()
            Group tab By groupDt = tab.Field(Of String)(groupBy) Into Group
            Select Group

'Getting Error
Dim test2 = From tab In m_oDataTable.AsEnumerable()
            Group tab By groupDt = tab.Field(Of String)(groupBy) Into Group
            Select New With 
            {
             .Grp = Key, ' Error in this line(Key is a type, cannot be used as a expression)
             .Sum = Group.Sum(Function(r) Double.Parse(r.Item("Time").ToString()))
            }

I tried in c# and got the desired result. But have no luck with VB :(

我在 c# 中尝试过并得到了想要的结果。但是 VB 没有运气:(

var test = from tab in m_oDataTable.AsEnumerable()
           group tab by tab.Field<string>(groupBy)
                 into groupDt
                 select new
                 {
                     Group = groupDt.Key,
                     Sum = groupDt.Sum(r => double.Parse(r["Time"].ToString()))
                 };

How to achieve this in VB?

如何在VB中实现这一点?

回答by Dave Williams

Not 100% sure why but VB.Net does not support .Key on query expression syntax. You actually define the key variable in the query. You are trying to use a variable "Key" which has not been defined. Instead you need to use they key you defined in the query (groupDt).

不是 100% 确定为什么,但 VB.Net 不支持 .Key 查询表达式语法。您实际上在查询中定义了关键变量。您正在尝试使用尚未定义的变量“Key”。相反,您需要使用它们在查询中定义的键 (groupDt)。

Change one small line and it should work...

更改一小行,它应该可以工作...

Select New With 
                {
                 .Grp = groupDt,
                 .Sum = Group.Sum(Function(r) Double.Parse(r.Item("Time").ToString()))
                }

OR you can use fluent syntax:

或者你可以使用流畅的语法:

Dim test2 = Table.AsEnumerable().GroupBy(Function(row) row.Item("Name1")).Select(Function(group) New With {.Grp = group.Key, .Sum = group.Sum(Function(r) Double.Parse(r.Item("Time").ToString()))})