Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.LastOrDefault: practical reference

Enumerable.LastOrDefault: practical reference: Returns the last element or predicate match; when absent it returns default(T) or an explicitly supplied default value.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

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

Returns the last element or predicate match; when absent it returns default(T) or an explicitly supplied default value.

Use it when absence of a last value is normal and distinguishable from a valid default.

A general source is enumerated to completion, so an infinite source never returns a result.

An empty source or no match returns default. A null source or predicate causes ArgumentNullException.

The complete program actually uses Enumerable.LastOrDefault; its exact expected stdout is 0.

Examples

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

Console.WriteLine(Array.Empty<int>().LastOrDefault());

Result

0

The complete program actually uses `Enumerable.LastOrDefault`; its exact expected stdout is `0`.

Sources