Introduction
In this article, Let’s fix some of the misconceptions about the four LINQ methods.
- Single() vs SingleOrDefault()
- First() vs FirstOrDefault().
These are the methods that we are using regularly in our code. However, if we don’t know their differences, we might be introducing some hidden bugs to our source code.
Misusing these methods can lead to two exceptions:
- Null References Exception
- Invalid Operator Exception
Note
- Single() returns the only element matching the predicate.
- First() returns the first element matching the predicate
To avoid this, we can use SingleOrDefault() and FirstOrDefault().
First() VS FirstOrDefault()
If there's no top performer in the employees' collection, a System.InvalidOperationException will be thrown by First(). Also, FirstOrDefault() returns the default value when there is no match, which is null in this case.
var topEmployee = employees.First(x=> x.IsTopPerformer); // First();
var topEmployee = employees.FirstOrDefault(x=> x.IsTopPerformer); // FirstOrDefault()
Single() VS SingleOrDefault()
If there's no employee with the username “Vishal” or if there is more than one employee with this username, a System.InvalidOperationException will be thrown by Single(). SingleOrDefault() handles this situation appropriately by returning a default value.
var employee = employees.Single(x=> x.UserName == "Vishal");
var employee = employees.SingleOrDefault(x=> x.UserName == "Vishal");
Summary
In this article, we have tried to cover misconceptions about the four LINQ methods.