<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged linq</title>
<link>https://coderlegion.com/tag/linq</link>
<description>Powered by Question2Answer</description>
<item>
<title>Sequence contains no elements</title>
<link>https://coderlegion.com/21746/sequence-contains-no-elements</link>
<description>&lt;p&gt;&lt;strong style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
    Today, we're going to fix a LINQ Error: &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; which the programmers encounter in daily life. It usually happens when we're using the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method to retrieve a value from a dataset. In this study blog, we'll explore why it happens and how to resolve it.
  &lt;/strong&gt;&lt;/p&gt;
&lt;div id=&quot;toc-div&quot;&gt;
  &lt;h4&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt; Table of Contents: &lt;a id=&quot;toc-toogle&quot; class=&quot;open&quot;&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/h4&gt;
  &lt;div id=&quot;toc-list&quot;&gt;
    &lt;ol&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;What is &quot;Sequence contains no elements&quot;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Causes&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;Solution&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Conclusion&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;The Reference&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774610&quot; id=&quot;_Toc123774610&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;What is &quot;Sequence contains no elements&quot;&lt;/span&gt; &lt;a id=&quot;TypeError-str-object&quot; style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774610&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This error happens we use &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; to retrieve a value but the value doesn't exist in the dataset. Let's look an example:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
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; }
        }
    }
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      First, I create a &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Student&lt;/em&gt; class with some properties.
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Alex&quot;).Single();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Then, I create a list of &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Student&lt;/em&gt; objects in my &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;program.cs&lt;/em&gt; and use the &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; to get the only &lt;em&gt;Student&lt;/em&gt; with name &lt;em&gt;Alex&lt;/em&gt;.
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-purple&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Note&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;We need to install &lt;em&gt;Newtonsoft&lt;/em&gt; library in the &lt;em&gt;Nuget Package&lt;/em&gt; so that we can use it to print out the &lt;em&gt;JSON string&lt;/em&gt; of our &lt;em&gt;Student&lt;/em&gt; object result.&lt;/span&gt;
  &lt;/div&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 {&quot;Name&quot;:&quot;Alex&quot;,&quot;Age&quot;:22,&quot;Gender&quot;:&quot;Male&quot;,&quot;Hobby&quot;:&quot;Basketball&quot;}
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Look, now we didn't get any errow because there's one &lt;em&gt;Student&lt;/em&gt; with name &lt;em&gt;Alex&lt;/em&gt;. Let's see another example:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).Single();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
System.InvalidOperationException: 'Sequence contains no elements'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Now, the &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; error occurs. Let's look at another example using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).First();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
System.InvalidOperationException: 'Sequence contains no elements'
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Same error occurs. Why? we'll see that next.
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774611&quot; id=&quot;_Toc123774611&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Causes&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774611&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Let's see the different types of errors that will be thrown while using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method:
    &lt;/span&gt;&lt;/p&gt;
  &lt;h3&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Single():&lt;/span&gt;&lt;/em&gt;&lt;/h3&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;ArgumentNullException: &lt;/em&gt;&lt;/strong&gt;Thrown when the source sequence is &lt;em&gt;null&lt;/em&gt;.&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;InvalidOperationException: &lt;/em&gt;&lt;/strong&gt;Thrown when the no element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; more than one element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; the source sequence is empty.&lt;/span&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;h3&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;First():&lt;/span&gt;&lt;/em&gt;&lt;/h3&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;ArgumentNullException: &lt;/em&gt;&lt;/strong&gt;Thrown when the source sequence is &lt;em&gt;null&lt;/em&gt;.&lt;/span&gt;&lt;/li&gt;
    &lt;li&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;&lt;strong&gt;&lt;em&gt;InvalidOperationException: &lt;/em&gt;&lt;/strong&gt;Thrown when no element satisfies the condition &lt;strong&gt;OR&lt;/strong&gt; the source sequence is empty.&lt;/span&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      According to the example on previous section, both &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; and &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt; method are getting the same error, that's &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;System.InvalidOperationException: 'Sequence contains no elements'&lt;/em&gt;&lt;/span&gt;. 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.
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774612&quot; id=&quot;_Toc123774612&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Solution&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774612&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      The solution is pretty simple, that's: instead of &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;Single()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;First()&lt;/em&gt;, use &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;SingleOrDefault()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt;. Instead of throwing the error &quot;&lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt;&quot;, they will return a &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;null&lt;/em&gt; value if no result found. Let's say:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).SingleOrDefault();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 null
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      and for &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt;:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).FirstOrDefault();
Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
Here is the result:
 null
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      Now, we can run our program without the error: &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; in the output. Although the condition is not met, we still can get a default object, which is &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;null&lt;/em&gt;. Looks, the solution is pretty simple right?
    &lt;/span&gt;&lt;/p&gt;
  &lt;div style=&quot;margin-top: 15px&quot; class=&quot;div-green&quot;&gt;
    &lt;span class=&quot;alert-header&quot;&gt;Tip&lt;/span&gt;
    &lt;span class=&quot;alert-body&quot;&gt;You can also execute some codes based on the object returned or return &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.notfound?view=aspnetcore-7.0&quot; target=&quot;_blank&quot;&gt;NotFound()&lt;/a&gt;&lt;/em&gt; if you're using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;ControllerBase&lt;/em&gt;.&lt;/span&gt;
  &lt;/div&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For instance:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
List students = new List()
{
      new Student(&quot;Alex&quot;, 22, &quot;Male&quot;, &quot;Basketball&quot;),
      new Student(&quot;Cindy&quot;, 20, &quot;Female&quot;, &quot;Badminton&quot;),
      new Student(&quot;Joshua&quot;, 20, &quot;Male&quot;, &quot;Swimming&quot;),
      new Student(&quot;Emily&quot;, 21, &quot;Female&quot;, &quot;Basketball&quot;),
      new Student(&quot;Josely&quot;, 22, &quot;Female&quot;, &quot;Jogging&quot;),
};

var result = students.Where(student =&amp;gt; student.Name == &quot;Clarence&quot;).FirstOrDefault();
if(result != null)
{
    Console.WriteLine($&quot;Here is the result:\n {Newtonsoft.Json.JsonConvert.SerializeObject(result)}&quot;);
}
else
{
    Console.WriteLine(&quot;The student is not found in the record!&quot;);
}
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      This is the result:
    &lt;/span&gt;&lt;/p&gt;
  &lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;
The student is not found in the record!
  &lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774613&quot; id=&quot;_Toc123774613&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Conclusion&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774613&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      In this study blog, we've learned what is &lt;span style=&quot;color: rgb(185, 106, 217);&quot;&gt;&lt;em&gt;Sequence contains no elements&lt;/em&gt;&lt;/span&gt; in LINQ, why it happens and how to resolve it. Note that using &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;SingleOrDefault()&lt;/em&gt; or &lt;em style=&quot;background-color: rgb(206, 212, 217); color: rgb(0, 0, 0);&quot;&gt;FirstOrDefault()&lt;/em&gt; is always better as they will not throw exception and terminate the program. Instead, they can help the programmers to check the output while executing the statement. Thank you and enjoy your day! :)
    &lt;/span&gt;&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
  &lt;h2&gt;&lt;a class=&quot;custom_anchor&quot; name=&quot;_Toc123774614&quot; id=&quot;_Toc123774614&quot;&gt;&lt;/a&gt;&lt;strong&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;The Reference&lt;/span&gt; &lt;a style=&quot;color: blue;&quot; rel=&quot;nofollow&quot; href=&quot;#_Toc123774614&quot;&gt;#&lt;/a&gt;&lt;/strong&gt;&lt;/h2&gt;
  &lt;p&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;
      For further information, please visit:
    &lt;/span&gt;&lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Serialization: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;Single() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.single?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.single?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;First() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;SingleOrDefault() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
    &lt;li&gt;&lt;em&gt;&lt;span style=&quot;font-family: arial, helvetica, sans-serif;&quot;&gt;FirstOrDefault() in LINQ: &lt;/span&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-7.0&quot; target=&quot;_blank&quot;&gt;https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=net-7.0&lt;/a&gt;&lt;/em&gt;&lt;/li&gt;
  &lt;/ol&gt;
&lt;/section&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/21746/sequence-contains-no-elements</guid>
<pubDate>Thu, 02 Jul 2026 06:40:00 +0000</pubDate>
</item>
<item>
<title>The Architectural Friction of LINQ to DataTables</title>
<link>https://coderlegion.com/20195/the-architectural-friction-of-linq-to-datatables</link>
<description>&lt;p&gt;Developers frequently bridge paradigms when working with legacy systems or enterprise reporting engines. A common intersection is executing modern language-integrated queries and streaming those results back into legacy tabular memory models. Directly casting a LINQ result set into a DataSet or DataTable is not natively supported out of the box, creating an immediate architectural hurdle for developers who assume fluid interoperability within the .NET ecosystem.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Architectural Breakdown &amp;amp; Challenges&lt;/strong&gt;&lt;br&gt;
Lack of Direct Type Alignment: Traditional DataTables require explicit schema definitions, whereas LINQ queries frequently yield anonymous types or strongly-typed generic collections. This structural disconnect prevents direct assignment.&lt;/p&gt;
&lt;p&gt;The CopyToDataTable Limitation: The standard .CopyToDataTable() extension method is strictly bound to IEnumerable. When your LINQ query projects customized object shapes or specific property subsets, this method throws compilation errors.&lt;/p&gt;
&lt;p&gt;Performance and Memory Overhead: Forcing structural conversion requires iterating through objects, parsing metadata via reflection, and manually mapping fields into data rows. This execution path risks high CPU utilization and heavy garbage collection pressure when processing massive datasets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Implementing the Optimal Solution&lt;/strong&gt;&lt;br&gt;
To solve this friction, developers must implement custom reflection-driven mapping utilities or leverage standard dynamic data tables. The modern, efficient way to bridge this gap involves creating a generic extension method that dynamically builds a schema from any collection of objects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;C#&lt;/strong&gt;&lt;br&gt;
using System;&lt;br&gt;
using System.Collections.Generic;&lt;br&gt;
using System.Data;&lt;br&gt;
using System.Reflection;&lt;/p&gt;
&lt;p&gt;public static class DataTableExtensions&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static DataTable ToDataTable&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; items)
{
    DataTable dataTable = new DataTable(typeof(T).Name);

    // Get all public properties of the type
    PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    // Define table schema based on property types
    foreach (PropertyInfo prop in Props)
    {
        // Handling nullable types correctly
        Type propType = prop.PropertyType;
        if (propType.IsGenericType &amp;amp;&amp;amp; propType.GetGenericTypeDefinition() == typeof(Nullable&amp;lt;&amp;gt;))
        {
            propType = Nullable.GetUnderlyingType(propType);
        }
        dataTable.Columns.Add(prop.Name, propType);
    }

    // Hydrate data table rows
    foreach (T item in items)
    {
        var values = new object[Props.Length];
        for (int i = 0; i &amp;lt; Props.Length; i++)
        {
            values[i] = Props[i].GetValue(item, null) ?? DBNull.Value;
        }
        dataTable.Rows.Add(values);
    }
    
    return dataTable;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
Dynamic Schema Generation: The generic extension reads object property metadata at runtime, ensuring your DataTable mirrors your LINQ projection perfectly without manual column definitions.&lt;/p&gt;
&lt;p&gt;Handling Nullable Types: The implementation explicitly checks for nullable value types, preventing standard initialization crashes when database fields contain missing or optional data.&lt;/p&gt;
&lt;p&gt;Streamlined Dataset Population: By calling .ToDataTable() directly on your LINQ query variable, the resulting standalone data table can be cleanly added to a broader DataSet container using standard .Tables.Add() methods.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Visit our official site: www.nextbigcreative.com&lt;/strong&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/20195/the-architectural-friction-of-linq-to-datatables</guid>
<pubDate>Wed, 10 Jun 2026 16:52:38 +0000</pubDate>
</item>
<item>
<title>Filling a DataSet or a DataTable from a LINQ Query Result Set</title>
<link>https://coderlegion.com/20001/filling-a-dataset-or-a-datatable-from-a-linq-query-result-set</link>
<description>&lt;p&gt;Modern .NET development often relies on LINQ (Language Integrated Query) to retrieve, filter, and transform data efficiently. LINQ provides a clean and readable way to work with collections, databases, XML files, and many other data sources. However, there are situations where applications still require traditional ADO.NET objects such as DataSet and DataTable for reporting, legacy integrations, or data binding purposes.&lt;/p&gt;
&lt;p&gt;Understanding how to fill a DataSet or DataTable from a LINQ query result set is an important skill when working with both modern and legacy .NET applications.&lt;/p&gt;
&lt;p&gt;Why Convert LINQ Results to DataTable or DataSet?&lt;/p&gt;
&lt;p&gt;LINQ queries typically return collections such as IEnumerable, IQueryable, or List. While these structures are excellent for application logic, some components require DataTable or DataSet objects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Common scenarios include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Reporting tools that accept DataTable as a data source.&lt;br&gt;
Legacy applications built around ADO.NET.&lt;br&gt;
Exporting data to Excel or CSV.&lt;br&gt;
Binding data to older UI controls.&lt;br&gt;
Data exchange between different application layers.&lt;/p&gt;
&lt;p&gt;Converting LINQ results into DataTable structures bridges the gap between modern querying techniques and traditional data handling mechanisms.&lt;/p&gt;
&lt;p&gt;Understanding LINQ Query Results&lt;/p&gt;
&lt;p&gt;Consider a simple list of employees:&lt;/p&gt;
&lt;p&gt;var employees = new List&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new Employee { Id = 1, Name = &quot;John&quot;, Department = &quot;IT&quot; },
new Employee { Id = 2, Name = &quot;Sarah&quot;, Department = &quot;HR&quot; },
new Employee { Id = 3, Name = &quot;David&quot;, Department = &quot;IT&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;};&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A LINQ query might look like:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;var result = from emp in employees&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;         where emp.Department == &quot;IT&quot;
         select emp;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This query returns a collection of Employee objects. To use this data in older systems, we may need to populate a DataTable.&lt;/p&gt;
&lt;p&gt;Creating a DataTable from LINQ Results&lt;/p&gt;
&lt;p&gt;The first step is creating the structure of the DataTable.&lt;/p&gt;
&lt;p&gt;DataTable dt = new DataTable();&lt;/p&gt;
&lt;p&gt;dt.Columns.Add(&quot;Id&quot;, typeof(int));&lt;br&gt;
dt.Columns.Add(&quot;Name&quot;, typeof(string));&lt;br&gt;
dt.Columns.Add(&quot;Department&quot;, typeof(string));&lt;/p&gt;
&lt;p&gt;After defining the columns, populate rows from the LINQ result.&lt;/p&gt;
&lt;p&gt;foreach (var employee in result)&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dt.Rows.Add(
    employee.Id,
    employee.Name,
    employee.Department
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;This approach gives complete control over the schema and data population process.&lt;/p&gt;
&lt;p&gt;Using CopyToDataTable()&lt;/p&gt;
&lt;p&gt;When LINQ operates directly on DataTable rows, .NET provides a built-in extension method called CopyToDataTable().&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;p&gt;DataTable employeesTable = GetEmployeesTable();&lt;/p&gt;
&lt;p&gt;var filteredRows =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from row in employeesTable.AsEnumerable()
where row.Field&amp;lt;string&amp;gt;(&quot;Department&quot;) == &quot;IT&quot;
select row;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;DataTable resultTable = filteredRows.CopyToDataTable();&lt;/p&gt;
&lt;p&gt;This method automatically creates a new DataTable and copies matching rows.&lt;/p&gt;
&lt;p&gt;Benefits include:&lt;/p&gt;
&lt;p&gt;Less code.&lt;br&gt;
Faster implementation.&lt;br&gt;
Preserves schema automatically.&lt;/p&gt;
&lt;p&gt;CopyToDataTable() is often the easiest solution when querying existing DataTable objects.&lt;/p&gt;
&lt;p&gt;Filling a DataSet with LINQ Results&lt;/p&gt;
&lt;p&gt;A DataSet can contain multiple DataTables.&lt;/p&gt;
&lt;p&gt;Create a DataSet:&lt;/p&gt;
&lt;p&gt;DataSet ds = new DataSet();&lt;/p&gt;
&lt;p&gt;Add the DataTable:&lt;/p&gt;
&lt;p&gt;ds.Tables.Add(dt);&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;You can also add multiple tables:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DataTable employeeTable = GetEmployeeData();&lt;br&gt;
DataTable departmentTable = GetDepartmentData();&lt;/p&gt;
&lt;p&gt;DataSet companyDataSet = new DataSet();&lt;/p&gt;
&lt;p&gt;companyDataSet.Tables.Add(employeeTable);&lt;br&gt;
companyDataSet.Tables.Add(departmentTable);&lt;/p&gt;
&lt;p&gt;DataSets are useful when managing related tables and complex reporting structures.&lt;/p&gt;
&lt;p&gt;Generic Method for Converting LINQ Results to DataTable&lt;/p&gt;
&lt;p&gt;A reusable generic solution can save development time.&lt;/p&gt;
&lt;p&gt;public static DataTable ToDataTable(IEnumerable data)&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DataTable table = new DataTable(typeof(T).Name);

PropertyInfo[] properties =
    typeof(T).GetProperties();

foreach (PropertyInfo property in properties)
{
    table.Columns.Add(
        property.Name,
        Nullable.GetUnderlyingType(property.PropertyType)
        ?? property.PropertyType);
}

foreach (T item in data)
{
    DataRow row = table.NewRow();

    foreach (PropertyInfo property in properties)
    {
        row[property.Name] =
            property.GetValue(item) ?? DBNull.Value;
    }

    table.Rows.Add(row);
}

return table;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;p&gt;var employeesDataTable = ToDataTable(result);&lt;/p&gt;
&lt;p&gt;This generic approach works with virtually any LINQ result collection.&lt;/p&gt;
&lt;p&gt;Performance Considerations&lt;/p&gt;
&lt;p&gt;When dealing with large datasets, performance becomes important.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Best practices include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Filter data at the database level whenever possible.&lt;br&gt;
Avoid unnecessary DataTable conversions.&lt;br&gt;
Use projections to select only required columns.&lt;br&gt;
Minimize reflection usage in high-performance scenarios.&lt;br&gt;
Cache metadata when repeatedly converting objects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example projection:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;var result =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;employees.Select(e =&amp;gt; new
{
    e.Id,
    e.Name
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This reduces memory consumption and processing overhead.&lt;/p&gt;
&lt;p&gt;Common Challenges&lt;/p&gt;
&lt;p&gt;Developers often encounter issues such as:&lt;/p&gt;
&lt;p&gt;Empty Query Results&lt;br&gt;
if(result.Any())&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DataTable table = result.CopyToDataTable();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;Calling CopyToDataTable() on an empty collection can throw an exception.&lt;/p&gt;
&lt;p&gt;Null Values&lt;/p&gt;
&lt;p&gt;Always handle null values properly:&lt;/p&gt;
&lt;p&gt;row[&quot;Name&quot;] =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;employee.Name ?? DBNull.Value;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Data Type Mismatches&lt;/p&gt;
&lt;p&gt;Ensure DataTable column types match source object properties to prevent runtime errors.&lt;/p&gt;
&lt;p&gt;Careful validation helps maintain data integrity and application stability.&lt;/p&gt;
&lt;p&gt;Real-World Applications&lt;/p&gt;
&lt;p&gt;Many enterprise applications still rely heavily on DataTables and DataSets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Typical use cases include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Financial reporting systems.&lt;br&gt;
Inventory management platforms.&lt;br&gt;
Business intelligence dashboards.&lt;br&gt;
Legacy Windows Forms applications.&lt;br&gt;
Data export utilities.&lt;br&gt;
Integration with third-party reporting engines.&lt;/p&gt;
&lt;p&gt;LINQ provides modern querying capabilities, while DataTable and DataSet maintain compatibility with established enterprise workflows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Filling a DataSet or DataTable from a LINQ query result set allows developers to combine the readability and flexibility of LINQ with the compatibility and structure of ADO.NET. Whether using manual row population, CopyToDataTable(), or generic conversion methods, understanding these techniques can significantly improve data processing workflows.&lt;/p&gt;
&lt;p&gt;As organizations continue modernizing their applications, developers frequently encounter environments where both LINQ and traditional ADO.NET coexist. Mastering the conversion between these technologies ensures smoother integrations, cleaner code, and more maintainable enterprise applications.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sumita&lt;br&gt;
Web Developer&lt;/strong&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/20001/filling-a-dataset-or-a-datatable-from-a-linq-query-result-set</guid>
<pubDate>Tue, 09 Jun 2026 04:50:51 +0000</pubDate>
</item>
</channel>
</rss>