Fixing LINQ Error: Sequence contains no elements

Posted by ChrisD on Geeks with Blogs See other posts from Geeks with Blogs or by ChrisD
Published on Tue, 15 Feb 2011 14:59:05 GMT Indexed on 2011/02/15 15:26 UTC
Read the original article Hit count: 369

Filed under:

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

© Geeks with Blogs or respective owner