Fixing LINQ Error: Sequence contains no elements
- by ChrisD
I’ve read some posts regarding this error when using the First() or Single() command. They suggest using FirstOrDefault() or SingleorDefault() instead. But I recently encountered it when using a Sum() command in conjunction with a Where(): Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Max(p => p.Amount); When the Where() function eliminated all the items in the policies collection, the Sum() command threw the “Sequence contains no elements” exception. Inserting the DefaultIfEmpty() command between the Where() and Sum(), prevents this error: Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p.Amount); but now throws a Null Reference exception! The Fix: Using a combination of DefaultIfEmpty() and a null check in the Sum() command solves this problem entirely: Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p => p==null?0 :p.Amount);