Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.Single: practical reference

Enumerable.Single: practical reference: Requires exactly one element or match and enumerates far enough to detect a second.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

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

Requires exactly one element or match and enumerates far enough to detect a second.

Use it to enforce result uniqueness, for example for a business key.

Single(source) calls MoveNext until it confirms the end after one element or sees a second; the predicate overload tests elements until a second match or the end. Iterator and predicate side effects run, and an infinite source with fewer than two matches may never terminate.

Zero or more than one result throws InvalidOperationException. A null source or predicate causes ArgumentNullException.

The complete program actually uses Enumerable.Single; its exact expected stdout is 2.

Examples

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

Console.WriteLine(new[] { 2, 7, 9 }.Single(value => value % 2 == 0));

Result

2

The complete program actually uses `Enumerable.Single`; its exact expected stdout is `2`.

Sources