C# Enumerable LastOrDefault(IEnumerable)

Description

Returns the last element of a sequence, or a default value if the sequence contains no elements.

Syntax


public static TSource LastOrDefault<TSource>(
  this IEnumerable<TSource> source
)

Parameters

  • TSource - The type of the elements of source.
  • source - An IEnumerable to return the last element of.

Returns

Returns the last element of a sequence, or a default value if the sequence contains no elements.

Example

The following code example demonstrates how to use LastOrDefault on an empty array.


// ww  w.  j ava  2 s  .c o  m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
     string[] fruits = { };
     string last = fruits.LastOrDefault();
     Console.WriteLine(String.IsNullOrEmpty(last) ? "<string is null or empty>" : last);

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable