LINQ DefaultIfEmpty Method in C#

LINQ DefaultIfEmpty Method in C#

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

LINQ DefaultIfEmpty Method in C#:

If the sequence or data source on which the DefaultIfEmpty method is called is not empty, then the values of the original sequence or data source are going to be returned. On the other hand, if the sequence or data source is empty, then it returns a sequence with the default values based on the data type. If this is not clear at the moment, then don’t worry, once we see some examples, then you will understand this very clearly. There are two overloaded versions available for this DefaultIfEmpty method in LINQ. They are as follows.

LINQ DefaultIfEmpty Method in C#

The first overloaded version does not take any parameter and in this case, if the sequence is empty then it will return the default values based on the data type. That means this method returns the elements of the specified sequence or the type parameter’s default value if the sequence is empty.

In the second overloaded version of the DefaultIfEmpty method, you can pass the default value and if the sequence is empty then this default value (what you pass to the method) is going to be returned by the DefaultIfEmpty method. That means this method returns the elements of the specified sequence or the specified value in if the sequence is empty.

Example to Understand LINQ DefaultIfEmpty Method in C#:

Let us see an example to understand LINQ DefaultIfEmpty Method in C# using both Method and Query Syntax. In the following example, the sequence is not empty. So, it is going to return a copy of the original values.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is not empty
            List<int> numbers = new List<int>() { 10, 20, 30 };

            //DefaultIfEmpty Method will return a new sequence with existing sequence values
            //Using Method Syntax
            IEnumerable<int> resultMS = numbers.DefaultIfEmpty();

            //Using Query Syntax
            IEnumerable<int> resultQS = (from num in numbers
                                        select num).DefaultIfEmpty();

            //Accessing the new sequence values using for each loop
            foreach (int num in resultMS)
            {
                Console.Write($"{num} ");
            }
            Console.ReadLine();
        }
    }
}

Output: 10 20 30

Example to Understand DefaultIfEmpty Method when Sequence is Empty:

Let us see an Example to Understand the DefaultIfEmpty Method when the Sequence is Empty. In the below example, the sequence is empty. So, in this case, it is going to return 0 as the default value. This is because 0 is the default value for the integer data type.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is empty
            List<int> numbers = new List<int>();

            //DefaultIfEmpty Method will return a new sequence with one element having the value 0
            //as the Sequence is Empty
            //Using Method Syntax
            IEnumerable<int> resultMS = numbers.DefaultIfEmpty();

            //Using Query Syntax
            IEnumerable<int> resultQS = (from num in numbers
                                        select num).DefaultIfEmpty();

            //Accessing the new sequence values using for each loop
            foreach (int num in resultMS)
            {
                Console.Write($"{num} ");
            }
            Console.ReadLine();
        }
    }
}

Output: 0

How to Supply User-Given Values when the Sequence is Empty?

In the following example, the sequence is empty but here we have supplied a default value (i.e. 5) to the DefaultIfEmpty method. So, in this case, the default value that we supplied (5) is going to be returned by the DefaultIfEmpty method.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is empty
            List<int> numbers = new List<int>();

            //DefaultIfEmpty Method will return 5 as the Sequence is Empty
            //as the Sequence is Empty
            //Using Method Syntax
            IEnumerable<int> resultMS = numbers.DefaultIfEmpty(5);

            //Using Query Syntax
            IEnumerable<int> resultQS = (from num in numbers
                                        select num).DefaultIfEmpty();

            //Accessing the new sequence values using for each loop
            foreach (int num in resultMS)
            {
                Console.Write($"{num} ");
            }
            Console.ReadLine();
        }
    }
}

Output: 5

What Happens if the Sequence is not Empty and we have Supplied a Value to the DefaultIfEmpty method?

If we supplied a default value but the sequence is not empty then, in that case, the original values that are present in the sequence are going to be returned. In the below example, we have supplied a default value i.e. 5 to the DefaultIfEmpty method but the sequence is not empty. So, in this case, the elements which are present in the sequence are going to be returned.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is not empty
            List<int> numbers = new List<int>() { 10, 20, 30 };

            //DefaultIfEmpty Method will return the Original Sequence values
            //as the Sequence is not Empty
            //Using Method Syntax
            IEnumerable<int> resultMS = numbers.DefaultIfEmpty(5);

            //Using Query Syntax
            IEnumerable<int> resultQS = (from num in numbers
                                        select num).DefaultIfEmpty();

            //Accessing the new sequence values using for each loop
            foreach (int num in resultMS)
            {
                Console.Write($"{num} ");
            }
            Console.ReadLine();
        }
    }
}

Output: 10 20 30

LINQ DefaultIfEmpty Method with Complex Type in C#:

Let us see an example to Understand How to use LINQ DefaultIfEmpty 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 LINQDefaultIfEmptyMethodDemo
{
    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"}
            };
        }
    }
}

Next, modify the Main method as follows. Here, we are creating a sequence by calling the GetAllEmployees method of the Employee class which is going to return 4 employees. That means our sequence is not empty. Then we created one employee object and pass that employee object to the DefaultIfEmpty method in case the sequence is empty. In this example, as the sequence is not empty, so the DefaultIfEmpty method is going to return the original sequence values.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is not empty
            List<Employee> employees = Employee.GetAllEmployees();

            //Create an Employee Object to pass into the DefaultIfEmpty method incase the sequence is Empty
            Employee emp5 = new Employee() { ID = 5, Name = "Hina", Salary = 10000, Gender = "Female" };

            //DefaultIfEmpty Method will return the Original Sequence values
            //as the Sequence is not Empty
            //Using Method Syntax
            IEnumerable<Employee> resultMS = employees.DefaultIfEmpty(emp5);

            //Using Query Syntax
            IEnumerable<Employee> resultQS = (from employee in employees
                                         select employee).DefaultIfEmpty(emp5);

            //Accessing the new sequence values using for each loop
            foreach (Employee emp in resultMS)
            {
                Console.WriteLine($"ID:{emp.ID}, Name:{emp.Name}, Gender:{emp.Gender}, Salary:{emp.Salary} ");
            }
            Console.ReadLine();
        }
    }
}

When you run the above application code, you will get the following output.

LINQ DefaultIfEmpty Method in C# with Examples

Now, modify the Main method as follows. Here, you can see, we are creating the sequence as Empty. So, in this case, the employee object we passed to the DefaultIfEmpty Method is going to be returned.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDefaultIfEmptyMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence is empty
            List<Employee> employees = new List<Employee>();

            //Create an Employee Object to pass into the DefaultIfEmpty method incase the sequence is Empty
            Employee emp5 = new Employee() { ID = 5, Name = "Hina", Salary = 10000, Gender = "Female" };

            //DefaultIfEmpty Method will return the Employee Object that we passed
            //as the Sequence is Empty
            //Using Method Syntax
            IEnumerable<Employee> resultMS = employees.DefaultIfEmpty(emp5);

            //Using Query Syntax
            IEnumerable<Employee> resultQS = (from employee in employees
                                         select employee).DefaultIfEmpty(emp5);

            //Accessing the new sequence values using for each loop
            foreach (Employee emp in resultMS)
            {
                Console.WriteLine($"ID:{emp.ID}, Name:{emp.Name}, Gender:{emp.Gender}, Salary:{emp.Salary} ");
            }
            Console.ReadLine();
        }
    }
}

Output: ID:5, Name:Hina, Gender:Female, Salary:10000

In the next article, I am going to discuss the LINQ SequenceEqual Operator in C# with Examples. In this article, I try to explain the LINQ DefaultIfEmpty Method in C# with Examples. I hope you understood the need and use of the LINQ DefaultIfEmpty Method in C# with Examples.

Leave a Reply

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