記錄一下以備往後需求:
Function GroupBy(ByVal i_sGroupByColumn As String, ByVal i_sAggregateColumn As String, ByVal i_dSourceTable As DataTable) As DataTable 'getting distinct values for group column Dim dv As New DataView(i_dSourceTable) 'adding column for the row count Dim dtGroup As DataTable = dv.ToTable(True, New String() {i_sGroupByColumn}) dtGroup.Columns.Add("Count", GetType(Integer)) 'looping thru distinct values for the group, counting For Each dr As DataRow In dtGroup.Rows dr("Count") = i_dSourceTable.Compute("Count(" & i_sAggregateColumn & ")", i_sGroupByColumn & " = '" & dr(i_sGroupByColumn) & "'") Next 'returning grouped/counted result Return dtGroup End Function
改了一個C#版本
public DataTable GroupBy(string i_sGroupByColumn, string i_sAggregateColumn, DataTable i_dSourceTable) { //getting distinct values for group column DataView dv = new DataView(i_dSourceTable); //adding column for the row count DataTable dtGroup = dv.ToTable(true, new string[] { i_sGroupByColumn }); dtGroup.Columns.Add("Count", typeof(int)); //looping thru distinct values for the group, counting foreach (DataRow dr in dtGroup.Rows) { string groupValueTemp = dr[i_sGroupByColumn].ToString(); if (String.IsNullOrEmpty(groupValueTemp) || groupValueTemp == "") { //欄位未填情形 groupValueTemp = "0"; } dr["Count"] = i_dSourceTable.Compute ("Count(" + i_sAggregateColumn + ")", i_sGroupByColumn + " = '" + groupValueTemp + "'"); } //returning grouped/counted result return dtGroup; }
Reference:
DataTable 中进行Distinct、Group by、Join、Create
Group By and Aggregates in .NET DataTable (最後採用的方法)
It would be nice to indicate the source of the function http://codecorner.galanter.net/2009/04/20/group-by-and-aggregates-in-net-datatable/
回覆刪除