Linq对DataTable中的列的分类统计
Linq 对DataTable中的列进行分类统计
一、构造数据源
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
dc.ColumnName = "Id";
dc.DataType = typeof(System.String);
dc.DefaultValue = "";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "CountIn";
dc.DataType = typeof(System.Decimal);
dc.DefaultValue = 0;
dt.Columns.Add(dc);
this.dataGridView1.DataSource = dt;
===============
二、添加数据
DataRow dr = dt.NewRow();
dr["Id"] = "a1";
dr["CountIn"] = 12;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = "B1";
dr["CountIn"] = 24;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = "a1";
dr["CountIn"] = 34;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Id"] = "B1";
dr["CountIn"] = 24;
dt.Rows.Add(dr);
========================
数据值:
=======================
三、分类汇总
var result = from r in dt.AsEnumerable()
group r by r.Field<string>("Id") into g
select new
{
g_id = g.Key,
g_countIn = g.Sum(r => r.Field<decimal>("CountIn"))
};
DataTable dt1 = dt.Clone();
DataRow dr;
foreach (var re in result)
{
dr = dt1.NewRow();
dr["Id"] = re.g_id;
dr["CountIn"] = re.g_countIn;
dt1.Rows.Add(dr);
}
this.dataGridView2.DataSource = dt1;
============================================
得到如下数据: