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();

VB.NET Code

 

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(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 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----

1

2

3

4

5

---List2 without Values---

0

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