Introduction:

 

In this article we will learn, how to DefaultIfEmpty() method in LINQ or what is DefaultIfEmpty() method in LINQ C# Asp.net MVC with example.

Description:

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

 

Example of LINQ DefaultIfEmpty() Method

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

 

using System;
using System.Collections.Generic;
using System.Linq;
namespace SQLTutorialsPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] List1 = { "A", "B", "C", "D", "E" };
            string[] List2 = { };
            var result = List1.DefaultIfEmpty();
            var result1 = List2.DefaultIfEmpty("None");
            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();
        }
    }
}

 

 

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

Now we will run and see the output.

Use LINQ DefaultIfEmpty Method


In this article we learned, 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.

 

I hope it will help to you after reading.

 

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like