转载:http://www.cnblogs.com/zq281660880/archive/2012/09/26/2704836.html
今天在使用linq处理一下需求时碰到一点小问题,特此记录。
需求:
按照品名相同的进行汇总,数量相加、表号按分号分割显示
1、组织测试数据表
DataTable tableA1 = new DataTable();
tableA1.Columns.AddRange(new DataColumn[] { new DataColumn("品名"), new DataColumn("规格"), new DataColumn("表号"),new DataColumn("数量") }); tableA1.Rows.Add(new object[] { "螺旋式", "LS-X", "111","2" }); tableA1.Rows.Add(new object[] { "螺旋式", "LS-X", "222","1" }); tableA1.Rows.Add(new object[] { "指针式", "LX-3", "523","2" }); tableA1.Rows.Add(new object[] { "其他式", "L-1", "666", "2" }); tableA1.Rows.Add(new object[] { "其他式", "L-1", "456", "1" }); tableA1.Rows.Add(new object[] { "其他式", "L-1", "990", "2" });
2、使用linq 进行查询处理
var query = from c in t.AsEnumerable()
group c by new { pingming = c.Field<string>("品名"), guige = c.Field<string>("规格") } into s select new { pingming = s.Select(p => p.Field<string>("品名")).First(), shuliang = s.Sum(p => Convert.ToInt32(p.Field<string>("数量"))), guige = s.Select(p => p.Field<string>("规格")).First(), biaohao = string.Join(";",s.Select(p => p.Field<string>("表号"))) }; DataTable tbl = tableA1.Clone(); query.ToList().ForEach(p => tbl.Rows.Add(p.pingming, p.guige,p.biaohao,p.shuliang));
查询结果: