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

Duplicates within an IEnumerable

Duplicates within an IEnumerable

Source

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;
            }
        }
    }
}

Example

var duplicates = list.GetDuplicates();

Author: Cătălin Rădoi

Submitted on: 18 jun. 2015

Language: C#

Type: IEnumerable

Views: 3859