下面是 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 表
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