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

5 thoughts on “Fixing LINQ Error: Sequence contains no elements”

  1. You will also get the “Sequence contains no elements” error when you attempt to execute any aggregate method on an empty set. For example:

    int maxRank = context.OpportunityRanks.Max(op => op.Rank.GetValueOrDefault());

    will yeild the exception if context.OpportunityRanks is an empty set. To correct this, I check the count of OpportunityRanks before executing the max method:

    int maxRank = context.OpportunityRanks==null?0: context.OpportunityRanks.Max(op => op.Rank.GetValueOrDefault());

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>