LINQ to SQL-';总和';在select new中
本文关键字:select new 总和 to LINQ SQL- | 更新日期: 2023-09-27 17:58:30
我有一个LINQ to SQL查询,它运行在一个表中,我想选择3个sum,即"Rate"answers"AdditionalCharges"的总和,所以我有这样的东西:
var sums = from d in dc.Deliveries
where d.TripDate == DateTime.Now
select new
{
Rate = d.Rate,
AdditionalCharges = d.AdditionalCharges
};
然而,很明显,这会为每次交付返回一个新行,这意味着我必须在之后对它们进行汇总——这似乎相当低效。有没有更简单的方法?
我知道这是一个老问题,但嘿,我找到了,所以希望这能帮助其他人。。。
您也可以使用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)
});
希望这能帮助到别人。。。
如果使用查询语法,可以执行以下
var data = dc.Deliveries.Where(d => d.TripDate == DateTime.Now)
var rateSum = data.Sum(d => d.Rate);
var additionalCharges = data.Sum(d => d.AdditionalCharges);
这是我的想法,没有测试
不确定,但您可以尝试以下中的分组再见功能
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)
};
您应该能够做到这一点:
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();
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