C# Linq LastorDefault Method

CsharpProgrammingServer Side Programming

Use the LastorDefault() method to return the last element of a sequence or a default value if element isn’t there.

The following is our empty list.

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

Now the following will not be able to display the last element since the list is empty. Therefore, the default would get display and error won’t be shown.

val.AsQueryable().LastOrDefault();

The following is the code.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<double> val = new List<double> { };
      double d = val.AsQueryable().LastOrDefault();
      Console.WriteLine("Default Value = "+d);
      if (d == 0.0D) {
         d = 0.1D;
      }
      Console.WriteLine("Default Value changed = "+d);
   }
}

Output

Default Value = 0
Default Value changed = 0.1
raja
Published on 14-Sep-2018 16:06:57
Advertisements