DataTable中多列的聚合函数

时间:2015-11-08 10:14:17

标签: c# asp.net

我在DataTable中有以下数据

Date   Date1           Visits     M      F
1Jan   2015-01-01      0          0      0
1Jan   2015-01-01      0          0      0
1Jan   2015-01-01      10         7      3
2Jan   2015-01-02      2          2      0
2Jan   2015-01-02      15         10     5
3Jan   2015-01-03      20         17     3

我想在VisitsMF和GROUP BY Date和Date1上应用聚合SUM函数。结果将是 -

Date    Date1        Visits     M      F
1Jan    2015-01-01   10         7      3
2Jan    2015-01-02   17         12     5
3Jan    2015-01-03   20         17     3

如何使用C#

中的DataTable实现这一目标

2 个答案:

答案 0 :(得分:1)

您可以使用LINQ to DataSet获得某种方式。以下假设dt是一个DataTable,其列名为“Day”,“Visits”,“M”和“F”:

var groupedByDay = dt.AsEnumerable().GroupBy(r => r.Field<string>("Day"));
foreach (var day in groupedByDay)
{
    var sumVisits = day.Select(r => r.Field<int>("Visits")).Sum();
    var sumMs = day.Select(r => r.Field<int>("M")).Sum();
    var sumFs = day.Select(r => r.Field<int>("F")).Sum();
    Console.WriteLine("{0}\t{1}\t{2}\t{3}", day.Key, sumVisits, sumMs, sumFs);
}

答案 1 :(得分:1)

试试这个; 您可以在dtNew(DataTable)中看到SUM结果。

DataTable dtNew =new DataTable("NewDataTable");
dtNew.Columns.Add("Date");
dtNew.Columns.Add("Date1");
dtNew.Columns.Add("Visits",typeof(int));
dtNew.Columns.Add("M",typeof(int));
dtNew.Columns.Add("F",typeof(int));


dt.AsEnumerable()
  .GroupBy(grp => new
    {
       Date = grp.Field<string>("Date"),
       Date1 = grp.Field<string>("Date1")
    })
   .Select(d =>
       {
         DataRow dr = dtNew.NewRow();
         dr["Date"] = d.Key.Date;
         dr["Date1"] = d.Key.Date1;
         dr["Visits"] = d.Sum(r => r.Field<int>("Visits"));
         dr["M"] = d.Sum(r => r.Field<int>("M"));
         dr["F"] = d.Sum(r => r.Field<int>("F"));
         return dr;
       })
    .CopyToDataTable(dtNew, LoadOption.OverwriteChanges);