CSharp - LINQ Last

Introduction

The Last operator returns the last element of a sequence or the last element of a sequence matching a predicate.

The Last operator always returns exactly one element, or it throws an exception if there is no last element to return.

Prototypes

There are two prototypes we cover. The first Last Prototype

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

Using this prototype, the Last operator enumerates the input sequence named source and returns the last element of the sequence.

The second prototype of Last uses a predicate:

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

This version of the Last operator returns the last element it finds for which the predicate returns true.

Exceptions

  • ArgumentNullException is thrown if any arguments are null.
  • InvalidOperationException is thrown if the source sequence is empty or if the predicate never returns true.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w w  w . j  a va2 s . co  m
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        string name = codeNames.Last();
        Console.WriteLine(name);
    }
}

Result

Related Topics