单个LINQ to SQL查询中的SUM和COUNT

时间:2016-10-07 07:10:16

标签: c# linq linq-to-sql

我正在尝试在LINQ-TO-SQL中创建以下查询。

select count(*), sum( o.CostInCents ) from Orders o
where Flag = true;

我提出了以下LINQ查询:

var q = db.Orders
    .Where(o => o.Flag )

var result = q
    .GroupBy(o => 1)
    .Select(g => new MyDTO
    {
        NoOfOrders = g.Count(),
        TotalInCents = g.Sum(o => o.CostInCents )
    })
    .SingleOrDefaultAsync();

有更好的方法吗?

.GroupBy(o => 1)是否还行?

另一种选择是做两个查询,如下所示。

var q = db.Orders
   .Where(o => o.Flag );

//No groupBy
var result2 = new MyDTO
{
    NoOfCostedOrders = q.Count(),//hit the db
    TotalInCents = q.Sum(o => o.CostInCents )//hit the db 2nd time
};

我应该如何判断哪种方法更好?

提前致谢!

3 个答案:

答案 0 :(得分:2)

This query can be rewritten in sql format as follows

var orderList = db.Orders.Where(o => o.Flag );
var orderSummary = from o in orderList
                   group o by 1 into p
                   select new
                   {
                      Items = p.Count(),
                      Total = p.Sum( x => x.CostInCents)
                   }

答案 1 :(得分:1)

我认为您要搜索的是以下一些细微调整:

var q = db.Orders
   .Where(o => o.Flag).Select(o => o.CostInCents).ToList(); // hit the db here once

//No groupBy
var result2 = new MyDTO
{
    NoOfCostedOrders = q.Count(), // don't hit the db
    TotalInCents = q.Sum() // don't hit the db a 2nd time
};

如果您对我的调整有疑问,请随时发表评论。

答案 2 :(得分:-1)

这样更干净:

var sum = q.Sum(x => x.CostInCents);
var count = q.Count();
如果结果是一个难以理解和混乱的代码,请不要坚持使用一个班轮。 而你通过w / c摆脱组是一个额外的开销