System.Linq.Enumerable.Distinct Method

Returns distinct elements from a sequence.

Method Signature

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)

Parameters

Returns

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

Exceptions

Remarks

The Distinct method skips duplicate values in the input sequence. For the first overload, it uses the default equality comparer for the element type to determine uniqueness. For the second overload, it uses the provided IEqualityComparer<TSource> to determine uniqueness.

The order of elements in the returned sequence is the same as their order in the source sequence. Only the first occurrence of each distinct element is preserved.

This method uses deferred execution. The sequence of distinct elements is not returned until the collection is enumerated.

Example

// Using the default equality comparer
int[] numbers = { 5, 3, 2, 5, 4, 3, 2, 1 };
IEnumerable<int> distinctNumbers = numbers.Distinct();
// distinctNumbers will contain { 5, 3, 2, 4, 1 }

// Using a custom equality comparer for strings (case-insensitive)
string[] words = { "apple", "Orange", "banana", "Apple", "orange" };
IEnumerable<string> distinctWords = words.Distinct(StringComparer.OrdinalIgnoreCase);
// distinctWords will contain { "apple", "Orange", "banana" }

See Also

See the System.Linq namespace for more LINQ functionality.
See the IEqualityComparer<T> interface.