星期一, 3月 22, 2010

[Asp.Net] Datatable Using Group By

今天剛好有需求要將取得的datatable再做group by,資料有點不好找。
記錄一下以備往後需求:


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 (最後採用的方法)

 

1 則留言:

  1. 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/

    回覆刪除

留個話吧:)