What is "Sequence contains no elements" #
This error happens we use Single() or First() to retrieve a value but the value doesn't exist in the dataset. Let's look an example:
internal class Student
{
private string name;
private int age;
private string gender;
private string hobby;
public Student(string name, int age, string gender, string hobby)
{
this.name = name;
this.age = age;
this.gender = gender;
this.hobby = hobby;
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public string Hobby
{
get { return hobby; }
set { hobby = value; }
}
}
First, I create a Student class with some properties.
List students = new List()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Alex").Single();
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
Then, I create a list of <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">Student</em> objects in my <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">program.cs</em> and use the <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">Single()</em> to get the only <em>Student</em> with name <em>Alex</em>.
</span></p>
<div style="margin-top: 15px" class="div-purple">
<span class="alert-header">Note</span>
<span class="alert-body">We need to install <em>Newtonsoft</em> library in the <em>Nuget Package</em> so that we can use it to print out the <em>JSON string</em> of our <em>Student</em> object result.</span>
</div>
<p><span style="font-family: arial, helvetica, sans-serif;">
This is the result:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
Here is the result:
{"Name":"Alex","Age":22,"Gender":"Male","Hobby":"Basketball"}
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
Look, now we didn't get any errow because there's one <em>Student</em> with name <em>Alex</em>. Let's see another example:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
List<Student> students = new List<Student>()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Clarence").Single();
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
This is the result:
System.InvalidOperationException: 'Sequence contains no elements'
Now, the Sequence contains no elements error occurs. Let's look at another example using First() method:
List students = new List()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Clarence").First();
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
This is the result:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
System.InvalidOperationException: 'Sequence contains no elements'
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
Same error occurs. Why? we'll see that next.
</span></p>
</section>
<section>
<h2><a class="custom_anchor" name="_Toc123774611" id="_Toc123774611"></a><strong><span style="font-family: arial, helvetica, sans-serif;">Causes</span> <a style="color: blue;" rel="nofollow" href="#_Toc123774611">#</a></strong></h2>
<p><span style="font-family: arial, helvetica, sans-serif;">
Let's see the different types of errors that will be thrown while using <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">Single()</em> or <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">First()</em> method:
</span></p>
<h3><em><span style="font-family: arial, helvetica, sans-serif;">Single():</span></em></h3>
<ul>
<li><span style="font-family: arial, helvetica, sans-serif;"><strong><em>ArgumentNullException: </em></strong>Thrown when the source sequence is <em>null</em>.</span></li>
<li><span style="font-family: arial, helvetica, sans-serif;"><strong><em>InvalidOperationException: </em></strong>Thrown when the no element satisfies the condition <strong>OR</strong> more than one element satisfies the condition <strong>OR</strong> the source sequence is empty.</span></li>
</ul>
<h3><em><span style="font-family: arial, helvetica, sans-serif;">First():</span></em></h3>
<ul>
<li><span style="font-family: arial, helvetica, sans-serif;"><strong><em>ArgumentNullException: </em></strong>Thrown when the source sequence is <em>null</em>.</span></li>
<li><span style="font-family: arial, helvetica, sans-serif;"><strong><em>InvalidOperationException: </em></strong>Thrown when no element satisfies the condition <strong>OR</strong> the source sequence is empty.</span></li>
</ul>
<p><span style="font-family: arial, helvetica, sans-serif;">
According to the example on previous section, both <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">Single()</em> and <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">First()</em> method are getting the same error, that's <span style="color: rgb(185, 106, 217);"><em>System.InvalidOperationException: 'Sequence contains no elements'</em></span>. This is because both of them can't find a value that meets the condition stated in the statement! So, how can we allow our program to run while this error is catched without being thrown at the output? Let's go to the next section.
</span></p>
</section>
<section>
<h2><a class="custom_anchor" name="_Toc123774612" id="_Toc123774612"></a><strong><span style="font-family: arial, helvetica, sans-serif;">Solution</span> <a style="color: blue;" rel="nofollow" href="#_Toc123774612">#</a></strong></h2>
<p><span style="font-family: arial, helvetica, sans-serif;">
The solution is pretty simple, that's: instead of <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">Single()</em> or <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">First()</em>, use <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">SingleOrDefault()</em> or <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">FirstOrDefault()</em>. Instead of throwing the error "<span style="color: rgb(185, 106, 217);"><em>Sequence contains no elements</em></span>", they will return a <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">null</em> value if no result found. Let's say:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
List<Student> students = new List<Student>()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Clarence").SingleOrDefault();
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
This is the result:
Here is the result:
null
and for FirstOrDefault():
List students = new List()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Clarence").FirstOrDefault();
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
This is the result:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
Here is the result:
null
</span></code></pre>
<p><span style="font-family: arial, helvetica, sans-serif;">
Now, we can run our program without the error: <span style="color: rgb(185, 106, 217);"><em>Sequence contains no elements</em></span> in the output. Although the condition is not met, we still can get a default object, which is <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">null</em>. Looks, the solution is pretty simple right?
</span></p>
<div style="margin-top: 15px" class="div-green">
<span class="alert-header">Tip</span>
<span class="alert-body">You can also execute some codes based on the object returned or return <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);"><a rel="nofollow" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.notfound?view=aspnetcore-7.0" target="_blank">NotFound()</a></em> if you're using <em style="background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);">ControllerBase</em>.</span>
</div>
<p><span style="font-family: arial, helvetica, sans-serif;">
For instance:
</span></p>
<pre><code><span style="font-family: arial,helvetica,sans-serif;">
List<Student> students = new List<Student>()
{
new Student("Alex", 22, "Male", "Basketball"),
new Student("Cindy", 20, "Female", "Badminton"),
new Student("Joshua", 20, "Male", "Swimming"),
new Student("Emily", 21, "Female", "Basketball"),
new Student("Josely", 22, "Female", "Jogging"),
};
var result = students.Where(student => student.Name == "Clarence").FirstOrDefault();
if(result != null)
{
Console.WriteLine($"Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}");
}
else
{
Console.WriteLine("The student is not found in the record!");
}
This is the result:
The student is not found in the record!