LINQ DefaultIfEmpty Method

  Total Views : 1463
  Comments : 0
  Keywords : Linq defaultifempty element operator method in c# / with example, How to use linq defaultifempty method in c# / to get element or default value from list / collection example

Here we will learn LINQ DefaultIfEmpt() method in c#, with example and how to use LINQ DefaultIfEmpty() method to get default value in case if list / collection contains null / empty or element from the sequenece in collection with example.

LINQ DefaultIfEmpty Method

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

Syntax of LINQ DefaultIfEmpty Method

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


C# Code


var result = List1.DefaultIfEmpty();



Dim result = List1.DefaultIfEmpty()

If you observe above example we are getting list items using LINQ DefaultIfEmpty method.

Example of LINQ DefaultIfEmpty Method

Following is the example of LINQ DefaultIfEmpty() method to get elements from list or return default value in case if no elements found in 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("---List2 without Values---");

foreach (var val2 in result1)










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("---List2 without Values---")

For Each val2 In result1




End Sub

End Module

If you observe 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 LINQ DefaultIfEmpty() method example.


----List1 with Values----






---List2 without Values---


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

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User