There are four famous concepts in LINQ, almost every C# developer knows about them and has used them in their daily development work.
I am talking about First and FirstOrDefault, Single and SingleOrDefault; these are all extension methods.
For this example, we created Employee class, declared some properties and defined a static method in Employee class.
Following is the Employee class:
- class Employee {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- }
Following is the array of Employee and it returns IEnumerable of Employee; i.e., IEnumerable<Employee>. Here is the hard-coded data, but you can get data from the database.
- public static IEnumerable < Employee > GetAllEmp() {
- IEnumerable < Employee > developers = new Employee[] {
- new Employee {
- Id = 101, Name = "Ashutosh"
- },
- new Employee {
- Id = 102, Name = "Nilesh"
- },
- new Employee {
- Id = 103, Name = "Amar"
- },
- new Employee {
- Id = 104, Name = "Ashutosh"
- },
- new Employee {
- Id = 105, Name = "Ashutosh"
- }
- };
- return developers;
- }
Let's start with First() and FirstOrDefault().
First()
It returns the first element from a sequence. It means when we query in a collection on specific criteria, if multiple elements are found in a collection of given criteria then the first element of a sequence will return.
- var emp = Employee.GetAllEmp().Where(x => x.Name == "Ashutosh").First();
- Console.WriteLine($ "Id:{emp.Id},Name:{emp.Name}");
In the above LINQ query, we are filtering employee name from the collection of Employees and if the filter criteria is matched, we get the below output on the console:
As you can see, there are three records in a sequence which match the input criteria but First() returns only the first element from the sequence.
In the above case we did positive testing, now we need to do negative testing with an invalid Employee Name.
Here, we are taking an employee which does not exist in our employee collection, let’s suppose it's Rahul.
- var emp = Employee.GetAllEmp().Where(x => x.Name == "Rahul").First();
- Console.WriteLine($ "Id:{emp.Id},Name:{emp.Name}");
When we run the console application we get an exception indicating the sequence contains no element.
So, if there is no record in the collection or database table which matches the input criteria, then First() method will throw an exception, because it can't handle the null value.
FirstOrDefault()
FirstOrDefault works same as First() does, FirstOrDefault returns the first element from a sequence, but here there is an advantage over First(), so if there is no record in the collection which matches input criteria then FirstOrDefault() can handle null values and it does not throw an exception.
Conclusion
Use First() when you are sure that a query must return a record, and use FirstOrDefault() when you are not sure whether it will return a record or not.
In the second part we will discuss Single() and SingleOrDefault()