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.
- static void Main(string[] args)
- {
- List<clsTest> lstTest = new List<clsTest>();
-
- lstTest.Add(new clsTest
- {
- Id = 1,
- Name = "A"
- });
- lstTest.Add(new clsTest
- {
- Id = 2,
- Name = "B"
- });
- lstTest.Add(new clsTest
- {
- Id = 3,
- Name = "C"
- });
-
-
- var fod = lstTest.Where(l => l.Name == "D").FirstOrDefault();
- var sod = lstTest.Where(l => l.Name == "D").SingleOrDefault();
- }
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.
- static void Main(string[] args)
- {
- List<clsTest> lstTest = new List<clsTest>();
-
- lstTest.Add(new clsTest
- {
- Id = 1,
- Name = "A"
- });
- lstTest.Add(new clsTest
- {
- Id = 2,
- Name = "B"
- });
- lstTest.Add(new clsTest
- {
- Id = 3,
- Name = "C"
- });
- lstTest.Add(new clsTest
- {
- Id = 4,
- Name = "C"
- });
-
- var fod = lstTest.Where(l => l.Name == "C").FirstOrDefault();
- var sod = lstTest.Where(l => l.Name == "C").SingleOrDefault();
- }
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.