LINQ is truly integrated into VB.NET. This allows not only to use LINQ-specific query language in a standard VB.NET code, but use VB.NET code in a LINQ query. Consider function from the previous post. To make it universal we can pass one more parameter
“Aggregate Type” and based on that parameter return Min, Max, Avg, Sum or Count
Function GroupBy(ByVal i_sGroupByColumn As String, ByVal i_sAggregateColumn As String, ByVal i_dSourceTable As DataTable, i_iAggregateType as Integer) As DataTable dim aQuery = From row In i_dSourceTable Group By Group1 = row(i_sGroupByColumn) Into Group Select Group1, Aggr = Choose(i_iAggregateType, Group.Min(Function(row) row(i_sAggregateColumn)), Group.Max(Function(row) row(i_sAggregateColumn)), Group.Sum(Function(row) row(i_sAggregateColumn)), Group.Avg(Function(row) row(i_sAggregateColumn)), Group.Count(Function(row) row(i_sAggregateColumn))) return aQuery.toDataTable End Function
In this example VB.NET function Choose is used inside of a LINQ query’s Select Statement. If i_iAggregateType parameter is equal 1 – Minimum value, will be calculated, 2 – Maximum etc.
Hi Yuriy,
Exactly what I’m looking for, thanks for the post. But please help me how to do this for multiple aggregation columns as well as multiple group by columns
@Phani – I haven’t tried this, but I beleive “Group By Group1 = …” should allow you to specify multiple columns. Also, similar to ” Aggr = …” you should be able to do something like ” Aggr1 = …, Aggr2 = …, Aggr3 = … ” to specify multiple aggregation results
Thanks Yuriy,
Will try that.