Linq 分组(group by)后列变行
表一:
表二:
已知表一的List,想得到表二的结果:
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));
附:lamada: var query = Templist.GroupBy(m => new { m.Id, m.FileName, m.Market, m.ShipId }).Select(gp => new { gp.Key.Id, gp.Key.FileName, gp.Key.Market, gp.Key.ShipId, Contactlist = string.Join(",", gp.Select(s => s.Contact).ToArray()) });