tym*_*tam 5 c# linq linq-to-sql
我正在尝试在LINQ-TO-SQL中创建以下查询。
select count(*), sum( o.CostInCents ) from Orders o
where Flag = true;
Run Code Online (Sandbox Code Playgroud)
我想出了以下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();
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
是.GroupBy(o => 1)即使OK?
另一个选择是执行两个查询,如下所示。
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
};
Run Code Online (Sandbox Code Playgroud)
我应该如何判断哪种方法更好?
提前致谢!
小智 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
};
Run Code Online (Sandbox Code Playgroud)
如果您对我的调整有疑问,请随时发表评论。
| 归档时间: |
|
| 查看次数: |
4254 次 |
| 最近记录: |