开发者

LINQ-to-SQL - 'Sum' inside a select new

开发者 https://www.devze.com 2023-03-11 03:17 出处:网络
I have a LINQ-to-SQL query that runs through a table, that I want to select 3 sum\'s - the sums of \'Rate\' and \'AdditionalCharges\', so I have something like this:

I have a LINQ-to-SQL query that runs through a table, that I want to select 3 sum's - the sums of 'Rate' and 'AdditionalCharges', so I have something like this:

var sums = from d in dc.Deliveries
where d开发者_运维技巧.TripDate == DateTime.Now
select new
{
    Rate = d.Rate,
    AdditionalCharges = d.AdditionalCharges
};

However, obviously this returns a new row for every delivery, which means I have to sum them up afterwards - which seems fairly inefficient. Is there an easier way?


I know that this is an old question, but hey, I found it, so hopefully this will help someone else...

You can also do this using Fluent syntax:

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)
                 });

Hope this helps someone...


If you use query syntax you can do something like the following

var data = dc.Deliveries.Where(d => d.TripDate == DateTime.Now)
var rateSum = data.Sum(d => d.Rate);
var additionalCharges = data.Sum(d => d.AdditionalCharges);

this is off the top of my head and not tested


Not sure but you can try out the group bye function as below

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)
};


You should be able to do this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消