Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.DistinctBy: practical reference

Enumerable.DistinctBy: practical reference: Like Distinct, but uniqueness is computed from the key returned by keySelector; the result contract is unordered.

Version: .NET 6+; verified on .NET 10.0.14

Syntax

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

Like Distinct, but uniqueness is computed from the key returned by keySelector; the result contract is unordered.

Use it to select one record per key value without first applying GroupBy.

The current implementation yields the first element for each key, but that is not an ordering guarantee. The selector runs during enumeration and the comparer applies to the key; incorrect equality merges records.

A null source or selector throws ArgumentNullException. An empty source yields no result, while null keys are handled by the comparer.

The complete program actually uses Enumerable.DistinctBy; its exact expected stdout is ant,bee.

Examples

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

Console.WriteLine(string.Join(",", new[] { "ant", "ape", "bee" }.DistinctBy(word => word[0])));

Result

ant,bee

The complete program actually uses `Enumerable.DistinctBy`; its exact expected stdout is `ant,bee`.

Sources