Tech Dreams

Fixing LINQ Error “Sequence contains no elements” [C#, LINQ]

Problem

When you query a LINQ data source with the Single() method call you may get the exception “System.InvalidOperationException: Sequence contains no elements”.

Cause

This exception is raised when there are no records that matches to the criteria specified in the LINQ query. For example the following LINQ query raises the exception if the where criteria does not match with any records in the data source

var objResultObject = (from RfVal in db.t_reference_values
                    where RfVal.id == plRefValId
                    select new { RfVal.description }).Single();

Solution

To solve the problem replace the method Single() call with SingleOrDefault() method. The method SingleOrDefault() returns a null value if there are no source records that matches to the filtering criteria.

var objResultObject = (from RfVal in db.t_reference_values
                    where RfVal.id == plRefValId
                    select new { RfVal.description }).SingleOrDefault();

13 Comments on Fixing LINQ Error “Sequence contains no elements” [C#, LINQ]

  1. A1 Shoaib
    May 15, 2012 at 2:27 pm (7 years ago)

    I am getting the Exception: Sequence contains no elements selected values from drop down list is not matched in DB. Any idea please … ?
    var sDate = (from bDate in _RSEnt.Reservations where bDate.SlotID == ddlSlot.SelectedItem.Value select bDate).ToList();

                    Reservation res = sDate.First();
                    startDate = Convert.ToDateTime(res.Day1.Value.ToShortDateString());
                    endDate = Convert.ToDateTime(res.Day3.Value.ToShortDateString());

                    if ( sDate != null)
                    {
                        if (e.Day.Date >= startDate.Date && e.Day.Date <= endDate.Date)
                        {
                            e.Day.IsSelectable = false;
                            e.Cell.BackColor = System.Drawing.Color.Red;
                        }
                    }
                    else
                    {
                        lblErr.Text = "Taa";
                    }

    Reply
  2. Victor E. Diaz
    August 22, 2011 at 8:34 pm (8 years ago)

    Thanks I resolved my issue with this post. Great contribution at the community.

    Reply
  3. pablo
    February 7, 2011 at 7:54 pm (8 years ago)

    Nice post, it helped me with a null exception, thanks!

    Reply
  4. PavanKumar Sriramula
    January 31, 2011 at 11:25 pm (8 years ago)

    Hello All,
    This problem might cause in wherein there are tables for Eg:Consider 2 tables, Employee Table which has EmploymentStatusId which is a foreign key referring EmploymentStatus table which has EmploymentStatusId column. Now when you run the Linq statement to set some value to EmploymentStatusId column of EmploymentStatus table which actually is not present in that table than you are supposed to get this kind of error.
    Thanks.
    PavanKumar Sriramula

    Reply
  5. jeevitha
    January 14, 2011 at 3:17 pm (8 years ago)

    thanks a lot..FirstOrDefault() method helped me a lot…:)

    Reply
  6. Irfan
    November 10, 2010 at 10:01 pm (9 years ago)

    It really helped a lot I stuck in this error on Live server…whoever sent this post deserves hats off.

    Reply
  7. Gregg
    July 8, 2010 at 2:29 pm (9 years ago)

    Awesome guys. I was wondering how to sort this out without Try/Catch blocks around all my LINQ queries, lol.

    Reply
  8. Amol
    June 24, 2010 at 6:38 pm (9 years ago)

    Thank you Jim & Gopinath for sharing this.

    Reply
  9. Roma
    October 18, 2009 at 9:40 pm (10 years ago)

    Thanks! this post helped me!

    Reply
  10. Kiran
    January 7, 2009 at 1:49 am (10 years ago)

    Thanks for the information.

    Reply
  11. Brian Brown
    November 5, 2008 at 12:20 am (11 years ago)

    Thanks for the tip Jim, I changed code to FirstOrDefault from SingleOrDefault to resolve the exception.

    Reply
  12. Gopinath Munisifreddy
    September 26, 2008 at 5:52 pm (11 years ago)

    Jim,
    Thank you very much for adding your views on fixing the problem. Using of FirstOrDefault() method makes more sense than SingleOrDefault().

    Reply
  13. Jim Wooley
    September 26, 2008 at 2:41 pm (11 years ago)

    Be careful with Single or SingleOrDefault. They will throw an exception if more than one record is found. You might want to consider First and FirstOrDefault instead.

    Another typical cause of the error you see is found when querying XML and not specifiying the namespace for the elements you are filtering on. It’s a common mistake that confuses many people.

    Reply

Leave a reply to PavanKumar Sriramula

Click here to cancel reply.