C# DefaultIfEmpty Method

CsharpProgrammingServer Side Programming

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
raja
Published on 14-Sep-2018 16:42:25
Advertisements