In Linq, a very interesting topic is Difference between First() and FirstOrDefault(), or we can say when to use First() and when FirstOrDefault() extention methods, you can check difference between Single() and SingleOrDefaul() here. So, Today I am going to explain these two extension method in Linq.
First()
It returns First element value from collection of elements or a sequence. It also returns first element of sequence when you specified condition. If result has no element than it will throws InvalidOperationException.
When to use First()
When you know that result contain more than 1 element expected and you should only the first element of sequence.
FirstOrDefault()
FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.
When to use FirstOrDefault()
When you know that output result contain more than 1 element and you should only the first element. Default value should be returned if no element is found.
Example
Use below example one by one to comment others.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqFirstAndFirstOrDefault
{
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
public class Program
{
static void Main(string[] args)
{
IList<Employee> employeeList = new List<Employee>(){
new Employee() { Id = 10, Name = "Chris", City = "London" },
new Employee() { Id=11, Name="Robert", City="London"},
new Employee() { Id=12, Name="Mahesh", City="India"},
new Employee() { Id=13, Name="Peter", City="US"},
new Employee() { Id=14, Name="Chris", City="US"}
};
//First example
var result1 = employeeList.First();
// It will return the first element like Id = 10, Name = "Chris", City = "London";
var result2 = employeeList.First(e => e.Id == 12);
// It will return the first element like Id=12, Name="Mahesh", City="India";
var result3 = employeeList.First(e => e.Name == "Chris");
//Two records available for Name=Chris but it will return the first like Id = 10, Name = "Chris", City = "London";
var result4 = employeeList.First(e => e.Id == 16);
//No element for Id=16 so, It throws an exception that Sequence contains more than one matching elemen
//FirstOrDefault example
var result5 = employeeList.FirstOrDefault();
// It will return the first element like Id = 10, Name = "Chris", City = "London";
var result6 = employeeList.FirstOrDefault(e => e.Id == 12);
// It will return the first element like Id=12, Name="Mahesh", City="India";
var result7 = employeeList.FirstOrDefault(e => e.Name == "Chris");
//Two records available for Name=Chris but it will return the first like Id = 10, Name = "Chris", City = "London";
var result8 = employeeList.FirstOrDefault(e => e.Id == 16);
//No element for Id=16 so, It return null for default;
Console.ReadLine();
}
}
}
Conclusion:
Today We learned what is difference between First() and FirstOrDefault() extention methods in Linq an when to use both of both of these.
I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and if you like this post, please share it with your friends. Thanks
Posted Comments :
MANISH JAIN Posted : 5 Years Ago
Thanks for sharing such a great article. In my last interview, I have been asked the same question.
MANISH JAIN Posted : 5 Years Ago
Thanks for sharing such a great article. In my last interview, I have been asked the same question.
Follower Posted : 5 Years Ago
Hi sir, I think your comment is wrong in here: var result4 = employeeList.First(e => e.Id == 16); //No element for Id=16 so, It throws an exception that Sequence contains more than one matching elemen Yes it probably throws an exception but not because of "Sequence contains more than one matching elemen " but because of something like "There are no element that matches your criteria". In your list you dont have records with Id 16.
Vasil Kosturski Posted : 5 Years Ago
I want to take a further step in interpreting the semantics of these methods. In my opinion FirstOrDefault() is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault() is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details https://vkontech.com/firstordefault-is-a-code-smell/. IMO most of the times SingleOrDefault() is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.
Mohamed sohail Posted : 3 Years Ago
I need full crud operation Sohail81249@gmail.com mail me sir
Akash Suresh Pawar Posted : 8 Years Ago
sir, you have any practical on MVC for CRUD operation using stored procedure.? Please mail me on my email id