Skip to main content

First, FirstOrDefault, Single, SingleOrDefault In C#

For people who are new to LINQ, it is difficult to understand the difference between First, FirstOrDefault, Single, SingleOrDefault. In this blog, I will explain what to use and when. 
  
I will take a simple example to make you understand practically how these methods work.
 
Consider a class Employee with properties as Id, Name, and Department.
  1. class Employee
  2. {
  3.    public int Id { getset; }
  4.    public string Name { getset; }
  5.    public string Department{ getset; }
  6. }
I have a list of Employees:
  1. List<Employee> employeeList = new List<Employee>(){
  2.    new Employee() { Id = 1, Name = "Sunny", Department = "Technical" },
  3.    new Employee() { Id=2, Name="Pinki", Department ="HR"},
  4.    new Employee() { Id=3, Name="Tensy", Department ="Finance"},
  5.    new Employee() { Id=4, Name="Bobby", Department ="Technical"},
  6.    new Employee() { Id=5, Name="Sweety", Department ="HR"}
  7. };
First()
  1. It returns the first element of a sequence.
  2. It throws an error when there is no element in the result, or source is null.
  3. We should use it if more than one element is expected and you want only the first element.
Ex 1
  1. var result = employeeList.First();
Will return
  1. Employee() { Id = 1, Name = "Sunny", Department = "Technical" }
Ex 2
  1. var result = employeeList.First(e=>e.Department== "HR");
Will return
  1. Employee() { Id=2, Name="Pinki", Department ="HR"}
Ex 3
  1. var result = employeeList.First(e=>e.Id == 8);
This will throw an error, because employee with Id as 8 does not exist in the employeeList.
 
FirstOrDefault()
  1. It returns the first element of a sequence, or a default value if no element is found.
  2. It throws an error only if the source is null.
  3. We should use it if more than one element is expected and you want only the first element. It's also good if the result is empty.
Example 1
  1. var result = employeeList.FirstOrDefault();
Will return:
  1. Employee() { Id = 1, Name = "Sunny", Department = "Technical" }
Example 2
  1. var result = employeeList.FirstOrDefault(e=>e.Department== "HR");
Will return:
  1. Employee() { Id=2, Name="Pinki", Department ="HR"}
Example 3
  1. var result = employeeList.FirstOrDefault(e=>e.Id == 8);
Will not throw an error but it returns default value of Employee.
 
Single()
  1.  It returns the only item of a sequence.
  2. This will throw an exception if the result contains 0 or more than 1 elements.
  3. We should use it, when we know that exactly one element is expected but neither 0 nor 2 or more.
Example 1
  1. var result = employeeList.Single(e=e.Id==1);
Will return:
  1. Employee() { Id = 1, Name = "Sunny", Department = "Technical" }
Example 2
  1. var result = employeeList.FirstOrDefault(e=>e.Department== "HR");
Will throw an exception as 2 employees exist with Department as "HR".
 
Example 3
  1. var result = employeeList.Single(e=>e.Id == 8);
Will throw an exception as no employee exists with Id as 8.
 
SingleOrDefault()
  1. It returns single specific element, and if the element is not found, it returns the default value of it.
  2. This will throw an exception if the result contains 2 or more elements.
  3. We should use it when we know that 0 or 1 element is expected as result.
Example 1
  1. var result = employeeList.SingleOrDefault(e=>e.Id == 1);
Will return
  1. Employee() { Id = 1, Name = "Sunny", Department = "Technical" }
Example 2
  1. var result = employeeList.SingleOrDefault(e=>e.Department== "HR");
Will throw an exception as 2 employees exist with Department as HR in employeeList.
 
Example 3
  1. var result = employeeList.SingleOrDefault(e=>e.Id == 8);
Will not throw an exception but it returns the default value of Employee.
 
I hope you understand the difference between First, FirstOrDefault and  Single, SingleOrDefault.

Comments

  1. Now, after the passing of so many years, the experts are seeking What Can Be the Future of Web Development 2020? What Primary or Tertiary Changes Are Going to Take Place? So, if you are ready to hire an Indian web development company then you must seek such acknowledgment among them.

    ReplyDelete
  2. Very good information given on his blogs and famous and trendy blogs with different categories
    click now

    ReplyDelete
  3. 1. I am very glad that I have come across such a beautifully designed article an full of fresh ideas and quality content
    Click for info

    ReplyDelete

Post a Comment

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first. We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server. In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user. Create the Project Open Visual Studio. File ->New -> Project Select C# -> Select Console Application Name the application as “EFGettingStarted” Click on OK Install Entity Framework The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command C# 1 2 3   install - package entityframework   This will install the late