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.

val.AsQueryable().FirstOrDefault();

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

Let us see the code.

Example

 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);
   }
}

Output

Default Value = 0
Default Float value updated = 0.1

Updated on: 23-Jun-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements