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
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());
looks like a decent fix, but it dint work on mine!!
Thank You so much..
I have referenced this blog post in an answer to a questions.
http://blog.sharepointsite.co.uk/2011/01/timesheet-solution-for-sharepoint-2010_19.html
thanks for the post
paul
Alternately we can check that query variable, using count method…