.NET API Documentation

System.Linq

Enumerable.DistinctBy Method

public static IEnumerable<TSource> DistinctBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector )

Summary

Returns distinct elements from a sequence based on a specified key selector function.

Description

This method filters a sequence to return only distinct elements. The determination of distinctness is based on the value returned by the keySelector function for each element. If multiple elements produce the same key, only the first element encountered in the sequence is included in the result.

This method is particularly useful when you want to remove duplicates based on a specific property or computed value of the elements, rather than the elements themselves.

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<TSource> from which to remove duplicate elements.
keySelector Func<TSource, TKey> A function to extract the key to compare the elements by.

Returns

Type Description
IEnumerable<TSource> An IEnumerable<TSource> that contains distinct elements from the source sequence.

Example


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

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Example
{
    public static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 30 },
            new Person { Name = "David", Age = 25 },
            new Person { Name = "Alice", Age = 35 }
        };

        // Get distinct people based on their Age
        var distinctByAge = people.DistinctBy(p => p.Age);

        Console.WriteLine("Distinct people by Age:");
        foreach (var person in distinctByAge)
        {
            Console.WriteLine($"- {person.Name} ({person.Age})");
        }
        // Output:
        // Distinct people by Age:
        // - Alice (30)
        // - Bob (25)

        // Get distinct people based on their Name
        var distinctByName = people.DistinctBy(p => p.Name);

        Console.WriteLine("\nDistinct people by Name:");
        foreach (var person in distinctByName)
        {
            Console.WriteLine($"- {person.Name} ({person.Age})");
        }
        // Output:
        // Distinct people by Name:
        // - Alice (30)
        // - Bob (25)
        // - Charlie (30)
        // - David (25)
    }
}
                

Remarks

The DistinctBy<TSource, TKey> method is an extension method introduced in .NET 6.

If the input sequence is empty, an empty IEnumerable<TSource> is returned.

The order of elements in the returned sequence is preserved relative to their order in the input sequence. The first occurrence of an element with a particular key is retained.