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 { get; set; }
  4.    public string Name { get; set; }
  5.    public string Department{ get; set; }
  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

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...

Extension methods in C#

Consider the class C# 1 2 3 4 5 6 7 8 9 10 11 12 13          namespace ExtensionMethod      {          public class testClass {              public string sayHello ( ) {              return "Hello" ;            }        }      }     Invoke the above from your form using C# 1 2 3 4 5 6          testClass test = new testClass ( ) ;      MessageBox . Show ( test . sayHello ( ) ) ;     This will show “Hello” in message box. Consider the scenario where you don...