Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 750
Chris Avatar asked Jun 06 '11 07:06

Chris


2 Answers

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

like image 93
NinjaNye Avatar answered Nov 02 '22 04:11

NinjaNye


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...

like image 29
Dan VanWinkle Avatar answered Nov 02 '22 04:11

Dan VanWinkle