LINQ DefaultIfEmpty Method

In LINQ, the DefaultIfEmpty operator is used to return the default value if the list/collection contains a null or empty value; otherwise, it will return elements from the sequence in the collection.

Syntax of LINQ DefaultIfEmpty Method

Following is the syntax of using the LINQ DefaultIfEmpty method to get list elements or show default values if the list returns empty or null values.

 

C# Code

 

var result = List1.DefaultIfEmpty();

VB.NET Code

 

Dim result = List1.DefaultIfEmpty()

If you observe the above example, we get list items using the LINQ DefaultIfEmpty method.

Example of LINQ DefaultIfEmpty Method

Following is the example of the LINQ DefaultIfEmpty() method to get elements from the list or return a default value if no elements are found in the list/collection.

 

C# Code

 

using System;
using System.Linq;
using System.Collections.Generic;

namespace LINQExamples
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] List1 = { 1,2,3,4,5 };
      int[] List2 = { };
      var result = List1.DefaultIfEmpty();
      var result1 = List2.DefaultIfEmpty();
      Console.WriteLine("----List1 with Values----");
      foreach (var val1 in result)
      {
        Console.WriteLine(val1);
      }
      Console.WriteLine("---List2 without Values---");
      foreach (var val2 in result1)
      {
        Console.WriteLine(val2);
      }
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1
Sub Main()
Dim List1 As Integer() = {1, 2, 3, 4, 5}
Dim List2 As Integer() = {}
Dim result = List1.DefaultIfEmpty()
Dim result1 = List2.DefaultIfEmpty()
Console.WriteLine("----List1 with Values----")
For Each val1 In result
Console.WriteLine(val1)
Next
Console.WriteLine("---List2 without Values---")
For Each val2 In result1
Console.WriteLine(val2)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above example, we have two lists list1, list2, and we are trying to get elements from these two lists using LINQ DefaultIfEmpty() method.

Output of LINQ DefaultIfEmpty() Method Example

Following is the result of the LINQ DefaultIfEmpty() method example.

 

----List1 with Values----
1
2
3
4
5 ---List2 without Values---
0

This is how we can use the LINQ DefaultIfEmpty() method in c#, vb.net to show the default value if the list or collection returns a null or empty value.