How to force LINQ Sum() to return 0 while source collection is empty

.net c# entity-framework

Question

In essence, the following query throws an exception if no leads were found when I run it. In such situation, I would rather the sum equate to zero than have an exception thrown. I mean rather than saving the query and checking, would this be doable in the query itself?query.Any() ?

double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                && l.Date.Month == date.Month
                && l.Date.Year == date.Year
                && l.Property.Type == ProtectedPropertyType.Password
                && l.Property.PropertyId == PropertyId).Sum(l => l.Amount);
1
178
7/11/2013 1:40:57 PM

Accepted Answer

ZZZ_tmp
381
7/11/2013 12:36:51 PM

Popular Answer

I'd rather employ a different trick:

double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                                      && l.Date.Month == date.Month
                                      && l.Date.Year == date.Year
                                      && l.Property.Type == ProtectedPropertyType.Password
                                      && l.Property.PropertyId == PropertyId)
                          .Sum(l => (double?) l.Amount) ?? 0;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow