What Was I Thinking?

Follies & Foils of .NET Development
posts - 85 , comments - 250 , trackbacks - 0

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

Print | posted on Tuesday, February 15, 2011 8:59 AM | Filed Under [ Visual Studio ]

Feedback

Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

You can get rid of the null check by using a Select before the Max.

var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Select(p => p.Amount).DefaultIfEmpty().Max();

You could also provide an explicit default value (and not have it just be some magic number in the Max predicate).

var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFloor).Select(p => p.Amount).DefaultIfEmpty(DefaultFloor).Max();
2/21/2011 1:02 AM | Ryan
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

good call, Ryan.

I like the idea of specifying my own default. Much more explicit.
2/21/2011 7:54 AM | wtfChris
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

Thanks, really helpfull!
5/12/2011 1:12 PM | Anonymous
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

Used Ryan's above solve using the Select/DefaultIfEmpty combo and it fixed it perfectly!
6/12/2012 3:15 PM | Kyle
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

Tanx !!!!
11/28/2012 4:31 AM | Anupriya
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

Thanks! You're the man!
1/10/2013 3:16 AM | Mike
Gravatar

# re: Fixing LINQ Error: Sequence contains no elements

Had an "aha!" moment once I read your fix Ryan. Thanks-A-Bunch!
3/24/2013 8:13 PM | Kelly
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: