Saturday, January 7, 2017

SingleOrDefault vs FirstOrDefault

LINQ provides with two extension methods SingleOrDefault and FirstOrDefault. Let's see the difference between the twoAdd a new class clsTest and add two properties Id and Name. Create a List clsTest type, add some data. So we have the following code:  
  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 access an element which does not exist in the list. Run the application and we get null. So both of these methods handle the null condition. Now let's add duplicate records and search the record. So the code changes to: 
  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. We get the exception Sequence contains more than one element for SingleOrDefault. FirstOrDefault returns the first matching record i.e. the record with Id=3. However, 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. Happy coding...!!!

No comments:

Post a Comment