using System.Collections.Generic;
public static void Main()
var list = new List<int> { 1, 2, 3, 4, 5, 2 };
var duplicates = list.GetDuplicates();
Console.WriteLine(string.Join(",", duplicates));
Console.WriteLine(string.Join(",", duplicates.Count()));
public static class Extensions
public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IEqualityComparer<TKey> comparer)
var hash = new HashSet<TKey>(comparer);
return source.Where(item => !hash.Add(selector(item))).ToList();
public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
return source.GetDuplicates(x => x, comparer);
public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
return source.GetDuplicates(selector, null);
public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source)
return source.GetDuplicates(x => x, null);