10

I am creating a method that collects accumulated totals throughout the month. The problem is that there may not be charges for some of the items in a given month so no rows would be returned.

I can see how this would error with no data:

double fuelCost = (double)(from a in db.EquipmentFuelLogs
                           where a.wdEquipmentMainGeneralOID == vehicleKey &&    
                                (monthBeginDate < a.Date1 && a.Date1 < monthEndDate)
                           select a.TotalCost).Sum();

What is the best approach to detect no fuel transactions for that month and set the fuel cost to 0? Just do a try catch? This article spoke of the problem but no solution.

Mike Wills
  • 20,959
  • 28
  • 93
  • 149

3 Answers3

18

The issue is because the where is returning no sequence therefor the sum cannot work, however if you use .DefaultIfEmpty before the sum it works fine.

decimal? orderValue = 
    orders.Where(ee => ee.Name == "SomeName").DefaultIfEmpty().Sum(s => s.OrderCost);

Hope this helps.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
David
  • 1
  • 1
  • 3
5

I resolved:

decimal orderValue = orders.Where(ee => ee.Name == "SomeName").Sum(s => (decimal?)s.OrderCost)??0;
Juan Carlos Velez
  • 2,840
  • 2
  • 34
  • 48
-10

I added a catch to catch the error. I never found a different solution.

Mike Wills
  • 20,959
  • 28
  • 93
  • 149