LINQ First and FirstOrDefault Methods in C#

LINQ First and FirstOrDefault Methods in C#

In this article, I am going to discuss the LINQ First and FirstOrDefault Methods in C# with Examples using both Method and Query Syntax. Please read our previous article where we discussed the LINQ ElementAt and ElementAtOrDefault Methods in C# with Examples.

LINQ First Method in C#: 

The LINQ First Method in C# is used to return the first element from a data source or from a collection. If the data source or collection is empty, or if we specified a condition and with that condition, no element is found in the data source, then the LINQ First method will throw an InvalidOperationException. If the Data Source is Null, then it will throw ArgumentNullException. There are two overloaded versions available for the LINQ First method as shown in the below image.

LINQ First Method in C#

As you can see, the first overloaded version does not take any parameter and it simply returns the first element from the data source. The second overloaded version takes a predicate as a parameter using which we can specify a condition and then it will return the first element which satisfied the specified condition. If no element satisfies the given condition, then it will throw an InvalidOperationException.

Example to Understand LINQ First Method in C#:

Let us see an example to Understand LINQ First Method in C# with both Method and Query Syntax. For a better understanding, please have a look at the following example. Here we have created one data source i.e. collection which contains integer numbers from 1 to 10.  Our requirement is to fetch the first element from the data source i.e. in the output we want to display the value 1 as it is the first element in the data source. And here, we fetch the first element from the collection using the LINQ First Method. There is no such operator called first available to write the Query Syntax, If you want then you can combine both the method syntax and query syntax to write the code which is also shown in the below example.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Fetching the First Element from the Data Source using First Method
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //Using Method Syntax
            int MethodSyntax = numbers.First();

            //Query Syntax
            int QuerySyntax = (from num in numbers
                               select num).First();

            //Printing the value returned by the First Method
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 1

Example to Understand LINQ First Method which takes Predicate as a Parameter in C#

Now, we need to fetch the first element from the data source which is divisible by 2. Here we need to use the second overloaded version of the First method using which we can specify our condition. For a better understanding, please have a look at the following example. The following program uses the second overloaded version to return the first element from the data source which is divisible by 2. See, there are many elements that satisfy the given condition, but the first element which satisfies the given condition is going to be returned by the First method. In this case, the element will be 2. In the below example, I am showing how to use the second overloaded version of the LINQ First method in C# using both Method and Query Syntax.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Fetching the First Element from the Data Source which is Divisble by 2
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //Using Method Syntax
            int MethodSyntax = numbers.First(num => num % 2 == 0);

            //Query Syntax
            int QuerySyntax = (from num in numbers
                               select num).First(num => num % 2 == 0);

            //Printing the value returned by the First Method
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 2

What Happens when we call the First Method on Empty Data Source?

Whenever the data source is empty, then the LINQ First Method will throw InvalidOperationException. For a better understanding, please have a look at the following example. In the below example, we are calling the First method on an Empty Data Source and hence when we run the following code, we will get one Runtime Exception.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Empty Data Source
            List<int> numbersEmpty = new List<int>() { };
            int MethodSyntax = numbersEmpty.First();
            Console.WriteLine(MethodSyntax);
            
            Console.ReadLine();
        }
    }
}
Output:

What Happens when we call the First Method on Empty Data Source?

What Happens If the Specified Condition in the First Method Does not Return any Data?

If the specified condition does not return any data, then the LINQ First Method will throw InvalidOperationException. For a better understanding, please have a look at the following example. In the below example, we are calling the First method and specifying the condition to fetch the first element which is greater than 50. As you can you see, the data source does not contain any element which is greater than 50, and hence when we run the below code, it will throw InvalidOperationException.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specified Condition Doesnot Return Any Element
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax = numbers.First(num => num > 50);
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}
Output:

What Happens If the Specified Condition in the First Method Does not Return any Data

Note: If you don’t want that Invalid Operation Exception, instead you want a default value based on the data type then you need to use the LINQ FirstOrDefault method. For the reference types, the default value is NULL and for the value types, the default value depends on the actual data type, for example, for numeric data types it is 0, for string data types, it is null, and for boolean data type, it is False.

LINQ FirstOrDefault Method in C#:

The LINQ FirstOrDefault Method in C# exactly does the same thing as the LINQ First method except that this method does not throw the InvalidOperationException exception when the data source is empty or when the specified condition does not match with any element in the data source. In such cases, it will return the default value based on the data type of the data source. If the Data Source is Null, then like the First Method, it will also throw ArgumentNullException. Like the First method, there are also two overloaded versions available for the FirstOrDefault method as shown below.

First and FirstOrDefault Methods in Linq

First Overloaded Version: It returns the first element of a sequence, or a default value if the sequence contains no elements.
First Overloaded Version: It returns the first element of the sequence that satisfies the given condition or a default value if no such element is found in the data source or if the data source is empty.

Example to Understand LINQ FirstOrDefault Method in C#.

Let us see an example to Understand LINQ FirstOrDefault Method in C# with both Method and Query Syntax. Our requirement is to fetch the First Element from the Data Source using FirstOrDefault Method. For a better understanding, please have a look at the following example. Here we have created one data source which contains integer numbers from 1 to 10. Then we need to fetch the first element from the collection using the FirstOrDefault method. There is no such operator called FirstOrDefault available to write the Query Syntax, If you want then you can combine both the method syntax and query syntax to write the code which is also shown in the below example.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //Using Method Syntax
            int MethodSyntax = numbers.FirstOrDefault();
            
            //Using Query Syntax
            int QuerySyntax = (from num in numbers
                               select num).FirstOrDefault();

            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 1

Example to Understand LINQ FirstOrDefault Method which takes Predicate as a Parameter in C#

Now, we need to fetch the first element from the data source which is greater than 5. Here we need to use the second overloaded version of the FirstOrDefault method using which we can specify our condition. For a better understanding, please have a look at the following example. The following program uses the second overloaded version of the LINQ FirstOrDefault to return the first element from the data source which is greater than 5. See, there are many elements that satisfy the given condition, but the first element which satisfies the given condition is 6 which is going to be returned by the FirstOrDefault method. In the below example, I am showing how to use the second overloaded version of the LINQ FirstOrDefault method in C# using both Method and Query Syntax.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //Using Method Syntax
            int MethodSyntax = numbers.FirstOrDefault(num => num > 5);
            
            //Using Query Syntax
            int QuerySyntax = (from num in numbers
                               select num).FirstOrDefault(num => num > 5);

            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 6

What Happens when we call the FirstOrDefault Method on Empty Data Source or when the condition does not satisfy any element?

Whenever the data source is empty, then the LINQ FirstOrDefault Method will not throw InvalidOperationException. Instead, it will return a default value based on the data type. Similarly, if no elements are found with the given condition then also it will not throw any exception, instead, it will also return the default value based on the data type.

For a better understanding, please have a look at the following example. In the below example, we have created two data sources. The first data source does not contain any item and here we are trying the fetch the first element. The second data source contains 10 elements from the numbers 1 to 10. From this data source, we are trying to retrieve the first element which is greater than 50.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Empty Data Source
            List<int> numbersEmpty = new List<int>();

            //Using Method Syntax
            int MethodSyntax1 = numbersEmpty.FirstOrDefault();
            
            //Using Query Syntax
            int QuerySyntax1 = (from num in numbersEmpty
                               select num).FirstOrDefault();

            Console.WriteLine(MethodSyntax1);
            
            //Specified condition doesnot return any element
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            //Using Method Syntax
            int MethodSyntax2 = numbers.FirstOrDefault(num => num > 50);
            
            //Using Query Syntax
            int QuerySyntax2 = (from num in numbers
                               select num).FirstOrDefault(num => num > 50);

            Console.WriteLine(MethodSyntax2);

            Console.ReadLine();
        }
    }
}

Here it will print the values as 0 and 0. This is because the data source contains integers. And the default for integers is 0.

LINQ First and FirstOrDefault Method with Complex Type in C#:

Let us see an example to Understand How to use LINQ First and FirstOrDefault Method with Complex Type in C#. For this, we are going to use the following Employee class. So, first, create a class file with the name Employee.cs and then copy and paste the following code into it. It is a very simple class having 4 properties and one method which is to return a collection of employees.

using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }

        public static List<Employee> GetAllEmployees()
        {
            return new List<Employee>()
            {
                new Employee { ID = 1, Name = "Preety", Salary = 10000, Gender = "Female"},
                new Employee { ID = 2, Name = "Priyanka", Salary =20000, Gender = "Female"},
                new Employee { ID = 3, Name = "Anurag", Salary = 35000, Gender = "Male"},
                new Employee { ID = 4, Name = "Pranaya", Salary = 45000, Gender = "Male"},
                new Employee { ID = 5, Name = "Hina", Salary = 10000, Gender = "Female"},
                new Employee { ID = 6, Name = "Sambit", Salary = 30000, Gender = "Male"},
                new Employee { ID = 7, Name = "Mahesh", Salary = 35600, Gender = "Male"}
            };
        }
    }
}
Example to Understand LINQ First Method with Complex Type in C#:

The following example shows how to use the LINQ First method (both overloaded versions) with Complex Type. The following Example code is self-explained, so please go through the comment lines for a better understanding.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Data Source
            List<Employee> listEmployees = Employee.GetAllEmployees();

            //Fetching the First Employee from listEmployees Collection
            Employee Employee1 = listEmployees.First();
            Console.WriteLine($"{Employee1.ID}, {Employee1.Name}, {Employee1.Gender}, {Employee1.Salary}");

            //Fetch the First Employee where the Gender is Male
            Employee Employee2 = listEmployees.First(emp => emp.Gender == "Male");
            Console.WriteLine($"{Employee2.ID}, {Employee2.Name}, {Employee2.Gender}, {Employee2.Salary}");

            //Fetch the First Employee where the Salary is less than 30000
            Employee Employee3 = listEmployees.First(emp => emp.Salary < 30000);
            Console.WriteLine($"{Employee3.ID}, {Employee3.Name}, {Employee3.Gender}, {Employee3.Salary}");

            Console.ReadLine();
        }
    }
}
Output:

Example to Understand LINQ First Method with Complex Type in C#

Example to Understand LINQ FirstOrDefault Method with Complex Type in C#:

The following example shows how to use the LINQ FirstOrDefault method (both overloaded versions) with Complex Type. The following Example code is self-explained, so please go through the comment lines for a better understanding.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQFirstOrDefaultMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Data Source
            List<Employee> listEmployees = Employee.GetAllEmployees();

            //Fetching the First Employee from listEmployees Collection
            Employee Employee1 = listEmployees.FirstOrDefault();
            Console.WriteLine($"{Employee1.ID}, {Employee1.Name}, {Employee1.Gender}, {Employee1.Salary}");

            //Fetch the First Employee where the Gender is Female
            Employee Employee2 = listEmployees.FirstOrDefault(emp => emp.Gender == "Female");
            Console.WriteLine($"{Employee2.ID}, {Employee2.Name}, {Employee2.Gender}, {Employee2.Salary}");

            //Fetch the First Employee where the Salary is greater than 30000
            Employee Employee3 = listEmployees.First(emp => emp.Salary > 30000);
            Console.WriteLine($"{Employee3.ID}, {Employee3.Name}, {Employee3.Gender}, {Employee3.Salary}");

            Console.ReadLine();
        }
    }
}
Output:

Example to Understand LINQ FirstOrDefault Method with Complex Type in C#

What is the Difference Between the First and FirstOrDefault Methods in LINQ?

Both First and FirstOrDefault methods in LINQ are used to return the first element from a data source. But if the data source is empty or if the specified condition does not return any data, then the First method will throw an exception while the FirstOrDefault method will not throw an exception instead it returns a default value based on the data type of the element.

In the next article, I am going to discuss the LINQ Last and LastOrDefault Methods in C# with Examples. In this article, I try to explain the First and FirstOrDefault method with some examples. I hope you understood the need and use of these two First and FirstOrDefault methods in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *