Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.Last: practical reference

Enumerable.Last: practical reference: Returns the last element or last predicate match; for a general IEnumerable<T> it normally reads the entire source.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

source.Last(/* overload-specific arguments */)

Returns the last element or last predicate match; for a general IEnumerable it normally reads the entire source.

Use it when absence is an error and the cost of complete enumeration is acceptable.

It never completes on an infinite source. For IList, the implementation can use indexing.

No result throws InvalidOperationException. A null source or predicate causes ArgumentNullException.

The complete program actually uses Enumerable.Last; its exact expected stdout is 6.

Examples

using System;
using System.Collections.Generic;
using System.Linq;

Console.WriteLine(new[] { 1, 4, 6, 3 }.Last(value => value % 2 == 0));

Result

6

The complete program actually uses `Enumerable.Last`; its exact expected stdout is `6`.

Sources