VB.NET & Linq: Sum datatable column and Group by date in another column
13,212
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 VarDate
because Date is reserved for it's own class.
Output:
Vardate: 10/15/2013 Worktime: 150
Vardate: 10/16/2013 Worktime: 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 on
on 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#
Comments
-
ruedi almost 2 years
I have a typedDataset (ds) and its datatable(dt). The datatable has the columns
Date
(ttmmyyy) andWorktime
. I want to sum the Worktime by month. I already accomplished to sum the Worktime withDim sum = dt.AsEnumerable().Sum((Function(x) x.Worktime))
I need help with group this by month.