Dec 16, 2011

Sequence contains no elements : LINQ error

If you are using LINQ or Lambda expression and getting error: InvalidOperationException “Sequence contains no elements”. It means you are trying to retrieve an element from an empty sequence(may be returned by LINQ query). There are some basic rules to handle this in LINQ or lambda expression.

1. If you are using Single in LINQ, change your habit to use SingleOrDefault.
2. If you are using First or Last in LINQ, use FirstOrDefault or LastOrDefault.
3. If you are using ElementAt, use ElementAtOrDefault.
4. If you are getting this error on Aggregate Functions like Average, Sum…etc.

To understand this, let us take an example. See following code.

var items = new int[] {1, 2, 3, 4, 5};
Double avg = items.Average();  

You will get avg = 3.0

Now, On adding where condition as in following, you will get error InvalidOperationException “Sequence contains no elements”.

Double avg = items.Where(x=>x > 10).Average(); 

because there is no item greater than 10. So what is the solution? Do you need to add one if condition every time to check whether items are available or not?
You need not to change code too much, Just use DefaultIfEmpty function before Aggregate Function.

 Double avg = items.Where(x=>x > 10).DefaultIfEmpty().Average(); 

Now, avg = 0.0

Hope, It helps.