用Group by获取Linq中字段的和
本文关键字:字段 Linq Group by 获取 | 更新日期: 2023-09-27 18:10:31
我有一个SQL:
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT, SUM(Amount) as AMNT
FROM Payments where (TYPE=1 AND Position=1) and (Date>='2011-01-01')
and (Date<='2012-01-01')
GROUP BY ApplicationNo
是否有一种方法,我可以在Linq转换相同的?
var q = (from payments in context.Payments
where payments.Date >= fromdate && payments.Date <= todate
group payments by new { payments.ApplicationId } into g
select new
{
applicationId=g.Key,
Amount=g.Sum(a=>a.Amount)
});
如果我在Linq中编写相同的内容,然后在最后进行分组,我不会得到相同的结果。
DateTime fromDate = new DateTime(2011, 1, 1);
DateTime toDate = new DateTime(2011, 1, 1);
var query = from p in db.Payments
where p.Type == 1 && p.Position == 1 &&
p.Date >= fromDate && p.Date <= toDate
group p by p.ApplicationNo into g
select new {
ApplicationNo = g.Key,
CNT = g.Count(),
AMNT = g.Sum(x => x.Amount)
};
这里db
是您的上下文类。