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 thoughts on “Fixing LINQ Error “Sequence contains no elements” [C#, LINQ]”

  1. 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";
                    }

  2. PavanKumar Sriramula

    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

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

  4. 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.

Leave a Comment

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