我有一个LINQ-to-SQL查询,它运行在一个表中,我想选择3个总和 - “Rate”和“AdditionalCharges”的总和,所以我有这样的东西:
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
select new
{
Rate = d.Rate,
AdditionalCharges = d.AdditionalCharges
};
然而,显然这会为每次传递返回一个新行,这意味着我必须在之后总结它们 - 这似乎效率很低。有更简单的方法吗?
答案 0 :(得分:15)
我知道这是一个老问题,但是嘿,我找到了,所以希望这会帮助别人......
您也可以使用Fluent语法执行此操作:
var sums = dc.Deliveries
.Where(d => d.TripDate == DateTime.Now)
.GroupBy(d => d.TripDate)
.Select(g =>
new
{
Rate = g.Sum(s => s.Rate),
AdditionalCharges = g.Sum(s => s.AdditionalCharges)
});
希望这有助于某人...
答案 1 :(得分:13)
如果使用查询语法,则可以执行以下操作
var data = dc.Deliveries.Where(d => d.TripDate == DateTime.Now)
var rateSum = data.Sum(d => d.Rate);
var additionalCharges = data.Sum(d => d.AdditionalCharges);
这是我的头脑而未经过测试
答案 2 :(得分:8)
不确定,但你可以尝试下面的分组再见功能
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
group d by new {d.Rate,d.AdditionalCharges,d.TripDate} into g
select new
{
Rate = g.Sum(s => s.Rate ),
AdditionalCharges = g.Sum(s => s.AdditionalCharges)
};
答案 3 :(得分:3)
你应该可以这样做:
DateTime d = DateTime.Now;
var sums = from d in dc.Deliveries
select new
{
Rate = dc.Deliveries.Where(n => n.TripDate == d).Sum(n => n.Rate),
AdditionalCharges = dc.Deliveries.Where(n => n.TripDate == d).Sum(n => n.AdditionalCharges)
};
var result = sums.FirstOrDefault();
答案 4 :(得分:0)
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
Group by d.TripDate // or primary key
Into TotalRate = sum(d.Rate),
TotalAdditionalCharges = sum(d.AdditionalCharges)
Select TotalRate , TotalAdditionalCharges