private System.Data.DataTable TestDataTable() { System.Data.DataTable oldDataTable = new DataTable(); oldDataTable.Columns.Add("CheckinNum"); oldDataTable.Columns.Add("CustomerAmount"); oldDataTable.Columns.Add("ProviderAmount"); oldDataTable.Columns.Add("AgentAmount"); oldDataTable.Columns.Add("GrossAmount"); oldDataTable.Columns.Add("TheMonth"); int N=17; //N行数据; System.Data.DataRow dr = oldDataTable.NewRow(); for (int i = 1; i < N; i++) { dr = oldDataTable.NewRow(); dr["CheckinNum"] = 1; dr["CustomerAmount"] = 2; dr["ProviderAmount"] = 3; dr["AgentAmount"] = 4; dr["GrossAmount"] = 5; dr["TheMonth"] = i<=12?i:1; oldDataTable.Rows.Add(dr); } return oldDataTable; //转换思路:把oldDataTable按1到12进行分类汇总,就是卡在这里了...,汇总用foreach() //形如: /* foreach (DataRow dr in oldDataTable.Rows) //关键点:根据(1 到12 月分来分类汇总,这里要怎样处理?? { int CheckinNum = Convert.ToInt32(dr["CheckinNum"]); this.totalCheckinNum += CheckinNum; ........................................ } */ }
Your have more questions!
Why not using sql statement to finish it?
You can use Linq method,for example 'GroupBy'!
//为了处理全量的12个月,那么先插入空数据 for (var i = 1; i <= 12; i++) { oldDataTable.Rows.Add(0, 0, 0, 0, 0, i);//补全数据 } var haha = oldDataTable.Rows.Cast<DataRow>().GroupBy(x => x["TheMonth"]) .Select(x => new { TheMonth = x.Key, CheckinNum = x.Sum(x1 => Convert.ToInt32(x1["CheckinNum"])), CustomerAmount = x.Sum(x1 => Convert.ToInt32(x1["CustomerAmount"])), ProviderAmount = x.Sum(x1 => Convert.ToInt32(x1["ProviderAmount"])), AgentAmount = x.Sum(x1 => Convert.ToInt32(x1["AgentAmount"])), GrossAmount = x.Sum(x1 => Convert.ToInt32(x1["GrossAmount"])) }).ToList(); //haha就是你需要的结果,是匿名类型的。
@幻天芒:
Works beautifully. Thanks!
The datatable from a procedure,and I not permission opera the database.
So I don't know the procedure contains what tables...
In addtion,I want to study linq method solve problem.
How to Convert var to DataTable?
我想从haha中得到DataTable后,增加一个合计行,
但haha是匿名类型的,我不会处理了,如果是table就可以用 foreach 计算出和。
@alone2013:
First,you must create a new 'DataTable' and add columns;
Second,you can use 'Select' method to add rows.
@幻天芒:
After created new 'DataTable',I don't know how convert the var to 'DataTable'...
@alone2013: Use loop
//定义匿名类型 var haha = new[] { 1, 2, 3, 4 }.Select(x => new { C1 = x, C2 = x * 2, C3 = x * 3 }); //转换为DataTable //创建DataTable并设定列 var dt = new DataTable(); dt.Columns.Add("C1", typeof(int)); dt.Columns.Add("C2", typeof(int)); dt.Columns.Add("C3", typeof(int)); //处理rows foreach (var x in haha) { dt.Rows.Add(x.C1, x.C2, x.C3); }
@幻天芒:
ok,I know.
Thank you so much for all your patience, guidance!