C# DefaultIfEmpty Method


This method is used to handle empty collections. Instead of showing an error, this method displays a default value.

We have the following list.

List<double> myList = new List<double>();

As you can see, since the above list is empty, we can display the default value.

var res = myList.DefaultIfEmpty();

Let us see an example.

Example

 Live Demo

using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      List<double> myList = new List<double>();
      var res = myList.DefaultIfEmpty();
      foreach (var a in res) {
         Console.WriteLine(a);
      }
   }
}

Output

0

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements