Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.Distinct: practical reference

Enumerable.Distinct: practical reference: Deferred enumeration returns the first occurrence of each value under the equality comparer and stores a set of keys already seen.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

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

Deferred enumeration returns the first occurrence of each value under the equality comparer and stores a set of keys already seen.

Use it for deduplication when retaining the first occurrence is desired under the current implementation.

Memory use is proportional to unique elements. Mutable keys and an inconsistent GetHashCode can produce incorrect results.

An empty source yields an empty result. Do not treat result order as a guaranteed sort order.

The complete program actually uses Enumerable.Distinct; its exact expected stdout is 2,1.

Examples

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

Console.WriteLine(string.Join(",", new[] { 2, 1, 2, 1 }.Distinct()));

Result

2,1

The complete program actually uses `Enumerable.Distinct`; its exact expected stdout is `2,1`.

Sources