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

Basically when I do the following query, if no leads were matched the following query throws an exception. In that case I’d prefer to have the sum equalize 0 rather than an exception being thrown.
Would this be possible in the query itself – I mean rather than storing the query and checking 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);

7 Answers
7

Leave a Comment