Linq 不分组 求和多列

.Net技术 码拜 8年前 (2016-05-29) 2190次浏览
下面是 Linq Group By 求和的C#代码,
var q = from p in dtQtyDetail.AsEnumerable()        //Linq Group By 求和汇总
group p by new
{
ColorID = p.Field<string>(“ColorID”)
} into g
select new
{
ColorID = g.Key.ColorID,
Qty1 = g.Sum(p => p.Field<Int16>(“Qty1”)),
Qty2 = g.Sum(p => p.Field<Int16>(“Qty2”)),
Qty3 = g.Sum(p => p.Field<Int16>(“Qty3”))
};
相当于 SQL:
select
ColorID,
SUM(Qty1)[Qty1],SUM(Qty2)[Qty2],SUM(Qty3)[Qty3]
from 表
group by ColorID

上面的代码没问题,
现在本人想不用分组了,想直接求和 Qty1 ,Qty2, Qty3 这3个字段
讨教 Linq 怎么样写?
即相当于 SQL:
select
SUM(Qty1)[Qty1],SUM(Qty2)[Qty2],SUM(Qty3)[Qty3]
from 表
解决方案

200

    var q = from p in dtQtyDetail.AsEnumerable()        
                        group p 1 into g
                        select new
                        { 
                            Qty1 = g.Sum(p => p.Field<Int16>("Qty1")),
                            Qty2 = g.Sum(p => p.Field<Int16>("Qty2")),
                            Qty3 = g.Sum(p => p.Field<Int16>("Qty3"))
                        };

finally you still using a “fake” group by :)


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Linq 不分组 求和多列
喜欢 (1)
[1034331897@qq.com]
分享 (0)