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

CsharpProgrammingServer Side Programming

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
raja
Published on 12-Sep-2018 12:30:22
Advertisements