VB.NET & Linq:在另一列中汇总数据表列和按日期分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19402993/
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 15:29:55  来源:igfitidea点击:

VB.NET & Linq: Sum datatable column and Group by date in another column

vb.netlinq

提问by ruedi

I have a typedDataset (ds) and its datatable(dt). The datatable has the columns Date(ttmmyyy) and Worktime. I want to sum the Worktime by month. I already accomplished to sum the Worktime with

我有一个 typedDataset (ds) 和它的数据表 (dt)。数据表具有列Date(ttmmyyy) 和Worktime. 我想按月总结工作时间。我已经完成了总结工作时间

Dim sum = dt.AsEnumerable().Sum((Function(x) x.Worktime))

I need help with group this by month.

我需要帮助按月分组。

回答by Carlos Landeras

I created a table with your fields and the following query worked nice:

我用您的字段创建了一个表,以下查询效果很好:

 Dim query = From row In dt
          Group row By VarDate= row.Field(Of DateTime)("Date") Into MonthGroup = Group
          Select New With {
              Key VarDate,
              .Worktime = MonthGroup.Sum(Function(r) r.Field(Of Int32)("Worktime"))
         }

Used variable VarDatebecause Date is reserved for it's own class.

使用变量,VarDate因为 Date 是为它自己的类保留的。

Output:

输出:

Vardate: 10/15/2013 Worktime: 150

Vardate: 10/16/2013 Worktime: 180

投票日:10/15/2013 工作时间:150

投票日:10/16/2013 工作时间:180

EDIT:

编辑:

To get the output just use:

要获得输出,只需使用:

 For Each obj In query
     Dim datet = obj.VarDate
     Dim WorkH = obj.Worktime
 Next

To avoid declarying types when using linq, insert the line: option infer onon the very first line of the vb.net document ( so you can use dim datet = obj.Vardate ) without declaring the type. It is like var in c#

为避免在使用 linq 时声明类型option infer on,请在 vb.net 文档的第一行插入行:(因此您可以使用 dim datet = obj.Vardate )而不声明类型。它就像 c# 中的 var