SingleOrDefault Vs FirstOrDefault In LINQ

In LINQ, we have the concept of SingleOrDefault and FirstOrDefault. Ever wondered what is the difference between the two? Let's try this with an example. We will create a class named clsTest and add two properties, Id and Name. Now, we create a List of its type, add some records and try both these methods. Thus, we have the code given below.
  1. static void Main(string[] args)  
  2.        {  
  3.            List<clsTest> lstTest = new List<clsTest>();  
  4.   
  5.            lstTest.Add(new clsTest  
  6.            {  
  7.                Id = 1,  
  8.                Name = "A"  
  9.            });  
  10.            lstTest.Add(new clsTest  
  11.            {  
  12.                Id = 2,  
  13.                Name = "B"  
  14.            });  
  15.            lstTest.Add(new clsTest  
  16.            {  
  17.                Id = 3,  
  18.                Name = "C"  
  19.            });  
  20.   
  21.   
  22.            var fod = lstTest.Where(l => l.Name == "D").FirstOrDefault();  
  23.            var sod = lstTest.Where(l => l.Name == "D").SingleOrDefault();  
  24.        }  
Here, we are trying to get an element which does not exist in the list. Now, if we run the application, we get the records as null. Thus, both of these methods handle the null condition. Now, let's add duplicate records and search the record. Thus, the code changes to what is  shown below.
  1. static void Main(string[] args)  
  2.         {  
  3.             List<clsTest> lstTest = new List<clsTest>();  
  4.   
  5.             lstTest.Add(new clsTest  
  6.             {  
  7.                 Id = 1,  
  8.                 Name = "A"  
  9.             });  
  10.             lstTest.Add(new clsTest  
  11.             {  
  12.                 Id = 2,  
  13.                 Name = "B"  
  14.             });  
  15.             lstTest.Add(new clsTest  
  16.             {  
  17.                 Id = 3,  
  18.                 Name = "C"  
  19.             });  
  20.             lstTest.Add(new clsTest  
  21.             {  
  22.                 Id = 4,  
  23.                 Name = "C"  
  24.             });  
  25.   
  26.             var fod = lstTest.Where(l => l.Name == "C").FirstOrDefault();  
  27.             var sod = lstTest.Where(l => l.Name == "C").SingleOrDefault();  
  28.         }  
Now, run the application and see the results. FirstOrDefault returns the first matching record; i.e., the record with Id=3. However, we get the exception given below or the SingleOrDefault - Sequence which contains more than one element. This is because, SingleOrDefault cannot handle the situation, if there are multiple elements with the same name. However, FirstOrDefault will return the first matching record from the list. This is the basic difference between the two. Happy coding.
Ebook Download
View all
Learn
View all