Kevin McNeish Blog

All things iOS, Kindle and .NET

Recent Posts

Tags

News

  • First books in my new book series, "iOS App Development for Non-Programmers" are now available! iBookStore: http://itunes.apple.com/us/book/book-1-diving-in-ios-app-development/id558788074?mt=11 Amazon: http://www.amazon.com/dp/B0097N8XBE Amazon: http://www.amazon.com/dp/B0099RQGMQ

Community

Email Notifications

Archives

Fixing LINQ Error: Sequence contains no elements

When you get theLINQ Error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

 Take for example the following code that uses First() on the results of the LINQ query. If there are no results, the call to First() triggers the "Sequenc contains no elements" error.:

var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().First();

To fix the problem, all you have to do is change First() to FirstOrDefault() which returns a null value when there are no results from the select:

var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().FirstOrDefault();

Kevin McNeish
INETA Speaker
.NET MVP 2002-2009
Chief Architect MM .NET Application Framework
www.oakleafsd.com

Comments

CS1401 said:

Thank You so much..

# January 9, 2012 6:36 AM

Paul Beck said:

I have referenced this blog post in an answer to a questions.

blog.sharepointsite.co.uk/.../timesheet-solution-for-sharepoint-2010_19.html

thanks for the post

paul

# January 10, 2012 12:40 PM
Leave a Comment

(required) 

(required) 

(optional)
 

(required) 

If you can't read this number refresh your screen
Enter the numbers above: