Wednesday, August 29, 2012

How to fix LINQ Error: Sequence contains no elements


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():

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:

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:
var effectiveFloor = policies.Where(p => p.PricingStrategy ==PricingStrategy.EstablishFloor).DefaultIfEmpty().Max(p =>  p==null?0 :p.Amount);


No comments:

Post a Comment