CSharp - LINQ LastOrDefault

Introduction

The LastOrDefault operator returns default value when an element is not found.

Prototypes

There are two prototypes we cover. The First LastOrDefault Prototype

public static T LastOrDefault<T>(
   this IEnumerable<T> source);

This version of the LastOrDefault returns the last element found in the input sequence.

If the sequence is empty, default(T) is returned.

For reference and nullable types, the default value is null.

The second prototype of the LastOrDefault operator uses a predicate to determine which element should be returned.

public static T LastOrDefault<T>(
  this IEnumerable<T> source,
  Func<T, bool> predicate);

Exceptions

ArgumentNullException is thrown if any arguments are null.

The following code uses LastOrDefault operator where no element is found.

We have to get an empty sequence by calling Take(0) for this purpose.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w  ww.ja  v a  2s . c om
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        string name = codeNames.Take(0).LastOrDefault();
        Console.WriteLine(name == null ? "NULL" : name);
        
        name = codeNames.LastOrDefault();
        Console.WriteLine(name == null ? "NULL" : name);
    }
}

Result

Related Topics