What Was I Thinking?

Follies & Foils of .NET Development
posts - 77, comments - 203, trackbacks - 0

My Links

News

Archives

Post Categories

Check These Out

Gurus

Tuesday, February 15, 2011

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

 

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);

Posted On Tuesday, February 15, 2011 8:59 AM | Feedback (3) | Filed Under [ Visual Studio ]

Powered by: