ExtensionMethod.NET Home of 876 C#, Visual Basic, F# and Javascript extension methods

Duplicates within an IEnumerable

Duplicates within an IEnumerable


public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> source) {
    HashSet<T> itemsSeen = new HashSet<T>();
    HashSet<T> itemsYielded = new HashSet<T>();

    foreach (T item in source) {
        if (!itemsSeen.Add(item)) {
            if (itemsYielded.Add(item)) {
                yield return item;


var duplicates = list.GetDuplicates();

Author: Cătălin Rădoi

Submitted on: 18 jun 2015

Language: C#

Type: IEnumerable

Views: 3660