找一个LINQ查询两列的总和找一个、总和、LINQ

2023-09-02 10:37:43 作者:伱的回眸一笑,豬都哭了

让我们说,我有一个称为表 项目(编号INT,完成INT,总INT)

let's say that I have a table called Items (ID int, Done int, Total int)

我可以通过两个查询做到这一点:

I can do it by two queries:

int total = m.Items.Sum(p=>p.Total)
int done = m.Items.Sum(p=>p.Done)

但我想这样做在一个查询中,是这样的:

But I'd like to do it in one query, something like this:

var x = from p in m.Items select new { Sum(p.Total), Sum(p.Done)};

当然,有一种方法调用从LINQ语法聚集函数...?

Surely there is a way to call aggregate functions from LINQ syntax...?

推荐答案

这将这样的伎俩:

from p in m.Items
group p by 1 into g
select new
{
    SumTotal = g.Sum(x => x.Total), 
    SumDone = g.Sum(x => x.Done) 
};