Linq: Sequence contains no matching element
Posted in Misc on March 26th, 2010 by taswar
So sometimes you will get these strange errors or exceptions when using linq.
For example if you use
1 | var result = myEnumerableCollection.First(x => x.Name == person.Name); |
This will throw InvalidOperationException with Sequence contains no matching element.
But if you use
1 2 3 | var result = myEnumerableCollection.FirstOrDefault(x => x.Name == person.Name); if(result == null) //did not find in the collection something went wrong or ..... |
Which will return you a null if its not found then you can check if the result is null and continue on with your work
Hope this helps
5 Responses
Leave a Comment

August 29th, 2010 at 5:58 pm
thanks this helped!
November 17th, 2010 at 12:43 am
Thanks very much, I started using it.
April 1st, 2011 at 8:25 am
Thank you! Exactly what i want!
November 17th, 2011 at 11:37 am
Didn’t work for me. I think my error was caused because my ICollection had no items.
November 17th, 2011 at 11:43 am
Turns Out First throws an exception if a list element can’t be found. MS Suggests using SingleOrDefault instead which will return null if no matching element is found.