Tutorialspoint

1 Answer
Chandu yadav
, 15 Views

To handle empty collections, use the DefaultIfEmpty() method in C#.

If an array is empty, then using this method will show the default method instead of displaying an error.

Let’s say we have an empty list.

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

Now, use DefaultIfEmpty() method to display the default value.

myList.DefaultIfEmpty();

Example

Live Demo

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

Output

0

Advertisements