205

I'm currently using a single query in two places to get a row from a database.

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).Single();

The query is fine when retrieving the row to put data in to the text boxes, but it returns an error "Sequence contains no elements" when used to retrieve the row in order to edit it and put it back in to the database. I can't understand why it might find an appropriate row in one instance but not another.

(Using ASP.NET MVC and LINQ)

David Basarab
  • 72,212
  • 42
  • 129
  • 156
  • 23
    you have to use SingleOrDefault , it will return null if no items returned – Mahmoud Farahat Dec 26 '12 at 09:24
  • the error is saying it can not find any items in dc.BlogPosts which match the value of ID. Either ID has no value or the items in your list contain that item. Use SingleOrDefault or FirstOrDefault, these will return a null object if no item if found rather than error. – prd82 Mar 09 '20 at 13:04
  • The question here is not to explain the meaning of "Sequence contains no elements", as many apparently think, but why it occurs. That question can't be answered because it lacks details. – Gert Arnold Jul 13 '22 at 18:10

7 Answers7

504

From "Fixing LINQ Error: Sequence contains no elements":

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

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()
V0d01ey
  • 47
  • 1
  • 6
Tony Kiernan
  • 5,157
  • 2
  • 14
  • 10
36

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

Angesehen
  • 301
  • 2
  • 16
Josue Morales
  • 711
  • 7
  • 6
13

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);
JoshJordan
  • 12,676
  • 10
  • 53
  • 63
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
13

In addition to everything else that has been said, you can call DefaultIfEmpty() before you call Single(). This will ensure that your sequence contains something and thereby averts the InvalidOperationException "Sequence contains no elements". For example:

BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == ID
                 select p).DefaultIfEmpty().Single();
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
bryc3monk3y
  • 424
  • 8
  • 12
10

This will solve the problem,

var blogPosts = (from p in dc.BlogPosts
             where p.BlogPostID == ID
             select p);
if(blogPosts.Any())
{
  var post = blogPosts.Single();
}
Matt Vukomanovic
  • 1,392
  • 1
  • 15
  • 23
Diganta Kumar
  • 3,637
  • 3
  • 27
  • 29
  • Hello , how can I solve error sequence contains no elements in my case if it is empty , can you check my case please this link : https://stackoverflow.com/questions/69621734/why-i-got-this-error-sequence-contains-no-elements/69621906#69621906 – Ziad Adnan Oct 19 '21 at 03:10
  • This will run the query twice on the database and there could then be a race condition. It's better to use `SingleOrDefault()` and then check for `null`. – Enigmativity Dec 31 '22 at 00:42
6

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();
Mihai Cristian
  • 115
  • 2
  • 10
2

Reason for error:

  1. The query from p in dc.BlogPosts where p.BlogPostID == ID select p returns a sequence.

  2. Single() tries to retrieve an element from the sequence returned in step1.

  3. As per the exception - The sequence returned in step1 contains no elements.

  4. Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.

  5. Since Single() is not able to fetch a single element from the sequence returned in step1, it throws an error.

Fix:

Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)

returns a sequence with at least one element.

Ali
  • 3,373
  • 5
  • 42
  • 54
Siddarth Kanted
  • 5,738
  • 1
  • 29
  • 20