CSharp - LINQ LastOrDefault


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


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


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.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from www. ja  v a2 s . co m
    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);


Related Topics