LINQ | Element Operator | FirstOrDefault

The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection.

The LINQ Standard Query Operator supports 8 types of element operators:

  1. ElementAt
  2. ElementAtOrDefault
  3. First
  4. FirstOrDefault
  5. Last
  6. LastOrDefault
  7. Single
  8. SingleOrDefault

FirstOrDefault Operator

The FirstOrDefault operator is used to return the first element of the given collection or sequence. Or it can also return the first element according to the given condition. And it provides a default value if the given collection or sequence does not contain any element or if the collection or sequence does not contain the element which specifies the given condition. Or we can say that the FirstOrDefault Operator is created to overcome the InvalidOperationException problem of the First operator. This method can be overloaded in two different ways:

  • FirstOrDefault<TSource>(IEnumerable<TSource>): This method returns the first element of the given sequence or collection without any condition. Or returns the default value if the given collection or sequence does not contain any element.
  • FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>): This method returns the first element which specifies the given condition. Or returns the default value if the collection does not contain the element which specifies the given condition.

Important Points:

  • It does not support query syntax in C# and VB.Net languages.
  • It support method syntax in both C# and VB.Net languages.
  • It present in both the Queryable and Enumerable class.
  • If the given collection contain a null element, then this method will throw an ArgumentNullException.
  • The default value of the reference types and the nullable types is null.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the 
// use of FirstOrDefault operator
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG {
  
    static public void Main()
    {
  
        // Data source
        int[] sequence1 = {112, 44, 55,
                      66, 77, 777, 56};
  
        // Get the element which specifies
        // the given condition
        // Using FirstOrDefault function
        var result1 = sequence1.FirstOrDefault(seq => seq < 77);
          
        Console.WriteLine("Value: {0}", result1);
  
        // Getting Default value because the
        // sequence does not contain any element
        int[] sequence2 = {};
          
        var result2 = sequence2.FirstOrDefault();
          
        Console.WriteLine("Default value: {0}", result2);
    }
}

chevron_right


Output:

Value: 44
Default value: 0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the name 
// of the first employee
using System;
using System.Linq;
using System.Collections.Generic;
  
// Employee details
public class Employee {
  
    public int emp_id
    {
        get;
        set;
    }
  
    public string emp_name
    {
        get;
        set;
    }
  
    public string emp_gender
    {
        get;
        set;
    }
  
    public string emp_hire_date
    {
        get;
        set;
    }
  
    public int emp_salary
    {
        get;
        set;
    }
}
  
class GFG {
  
    // Main method
    static public void Main()
    {
        List<Employee> emp = new List<Employee>() {
              
            new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female",
                                    emp_hire_date = "12/3/2017", emp_salary = 20000},
  
            new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female",
                                    emp_hire_date = "22/4/2018", emp_salary = 30000},
  
            new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male",
                                  emp_hire_date = "3/5/2016", emp_salary = 40000},
  
            new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female",
                                    emp_hire_date = "4/8/2017", emp_salary = 40000},
  
            new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male",
                                emp_hire_date = "12/1/2016", emp_salary = 40000},
  
            new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female",
                                  emp_hire_date = "17/6/2015", emp_salary = 50000},
        };
  
        // Query to find the name the first 
        // employee Using FirstOrDefault method
        var res = emp.Select(e => e.emp_name).FirstOrDefault();
          
        Console.WriteLine("Employee Name: {0}", res);
    }
}

chevron_right


Output:

Employee Name: Anjita


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.