今天有同事问,如何在datatable中进行分组,并且计算分组后每组的数量,想了一下,可以使用LINQ来实现datatable分组。代码如下
效果
区域 库房 数量
北京---北京仓库---1
北京---上海仓库---1
上海---上海仓库---2
DataTable dt = new DataTable("cart");
DataColumn dc1 = new DataColumn("areaid", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("house", Type.GetType("System.String"));
DataColumn dc3 = new DataColumn("seq", Type.GetType("System.String"));
DataColumn dc4 = new DataColumn("remark", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
DataRow dr = dt.NewRow();
dr["areaid"] = "北京";
dr["house"] = "北京仓库";
dr["seq"] = "2";
dr["remark"] = "货到付款";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["areaid"] = "北京";
dr1["house"] = "上海仓库";
dr1["seq"] = "1";
dr1["remark"] = "货到付款";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["areaid"] = "上海";
dr2["house"] = "上海仓库";
dr2["seq"] = "1";
dr2["remark"] = "货到付款";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["areaid"] = "上海";
dr3["house"] = "北京仓库";
dr3["seq"] = "1";
dr3["remark"] = "货到付款";
dt.Rows.Add(dr3);
var query = from t in dt.AsEnumerable()
group t by new { t1 = t.Field<string>("areaid"), t2 = t.Field<string>("seq") } into m
select new
{
areaid = m.Key.t1,
seq = m.Key.t2,
house = m.First().Field<string>("house"),
rowcount = m.Count()
};
Console.WriteLine("区域 "+" 库房"+" 数量");
foreach (var item in query.ToList())
{
if (item.rowcount>1)
{
MessageBox.Show(item.areaid+"---"+item.house);
}
Console.WriteLine(item.areaid+"---"+item.house+"---"+item.rowcount);
Console.WriteLine("\r\n");
}