C#如何将总行添加到数据表中

时间:2016-10-14 03:44:42

标签: c# linq datatable

我有一张这样的表

BookingDate  Status  BookingNumber  
----------------------------------   
2016/10/14    1         3  
2016/10/14    1         1  
2016/10/14    1         5  
2016/10/13    1         7  
2016/10/13    1         4  
2016/10/12    1         8  
2016/10/12    1         3  
2016/10/12    1         6  
2016/10/12    1         2  

我想通过BookingDate分组并计算BookingNumber。 在数据表中添加新行

 BookingDate  Status  BookingNumber
    ----------------------------------------
    2016/10/14    1         3
    2016/10/14    1         1
    2016/10/14    1         5
    2016/10/14   Total      9
    2016/10/13    1         7
    2016/10/13    1         4
    2016/10/14   Total      11
    2016/10/12    1         8
    2016/10/12    1         3
    2016/10/12    1         6
    2016/10/12    1         2
    2016/10/14   Total      19

这是我的LinqPad示例代码:

ProcessInfo.processInfo.physicalMemory

我不知道Linq能够做到这一点吗? 或者只是使用for循环来插入新行。

2 个答案:

答案 0 :(得分:1)

就个人而言,我不会将其存储在同一个表中。相反,我会有一个单独的表(可能称为OrderTotals?)跟踪预订总数。每个订单都可以有一个外键引用其相应总计记录的主键。

但是如果你真的想在同一个表中存储总数,那么我会为它定义一个额外的可选列。

答案 1 :(得分:0)

我终于解决了这个问题。

void Main()
{
    DataTable workTable = new DataTable("Order");

    DataColumn workCol = workTable.Columns.Add("BookingDate", typeof(String));
    workTable.Columns.Add("Status", typeof(String));
    workTable.Columns.Add("BookingNumber", typeof(int));
    workTable.Rows.Add("2016/10/14","1",3);
    workTable.Rows.Add("2016/10/14","1",1);
    workTable.Rows.Add("2016/10/14","1",5);
    workTable.Rows.Add("2016/10/13","1",7);
    workTable.Rows.Add("2016/10/13","1",4);
    workTable.Rows.Add("2016/10/12","1",8);
    workTable.Rows.Add("2016/10/12","1",3);
    workTable.Rows.Add("2016/10/12","1",6);
    workTable.Rows.Add("2016/10/12","1",2);

    //========統計人數
var count=workTable.AsEnumerable()
.Select(x=>new { BookingDate= x.Field<string>("BookingDate"),BookingNumber = x.Field<int>("BookingNumber")})
.GroupBy(x=>x.BookingDate)
.Select(x=>new{BookingDate=x.Key,BookingNumber=x.Sum(s=>s.BookingNumber),Index=x.Count()}).OrderByDescending(x=>x.BookingDate).ToList();

count.Dump();
//========插入新的row
int Position=0;
foreach(var obj in count){
    DataRow dr = workTable.NewRow();

    dr[0] = obj.BookingDate;
    dr[1] = "Total";
    dr[2] = obj.BookingNumber;
    Position +=obj.Index;
    workTable.Rows.InsertAt(dr, Position);
    Position++;
}

workTable.Dump();

}