Display the default if element is not found in a C# List

We have a list without any element.

List<float> val = new List<float> { };

To display the default and avoid any error, use the FirstorDefault() method.


You can also change the value to be displayed as default.

Let us see the code.


 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<float> val = new List<float>{ };
      float a = val.AsQueryable().FirstOrDefault();
      Console.WriteLine("Default Value = "+a);
      if (a == 0.0f) {
         a = 0.1f;
      Console.WriteLine("Default Float value updated = "+a);


Default Value = 0
Default Float value updated = 0.1