LINQ provides with two extension methods SingleOrDefault and FirstOrDefault. Let's see the difference between the two. Add 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:
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:
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...!!!