How to handle empty collections in C#


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

Updated on: 23-Jun-2020

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements