Skip to content

Instantly share code, notes, and snippets.

@kavun
Created July 31, 2015 14:43
Show Gist options
  • Save kavun/82472d470c13c3494ee5 to your computer and use it in GitHub Desktop.
Save kavun/82472d470c13c3494ee5 to your computer and use it in GitHub Desktop.
Use HashSet<T>.Add with a custom EqualityComparer<T> to efficiently find duplicates
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var items = new List<Item>() {
new Item() { Name = "test" },
new Item() { Name = "test" },
new Item() { Name = "test" },
new Item() { Name = "test2" },
new Item() { Name = "test2" },
new Item() { Name = "test3" }
};
var duplicates = GetDistinctDuplicates(items, new ItemNameComparator());
Console.WriteLine(String.Join(", ", duplicates.Select(i => i.Name)));
Console.ReadLine();
}
public class Item
{
public string Name { get; set; }
}
public static IEnumerable<T> GetDistinctDuplicates<T>(IEnumerable<T> items, IEqualityComparer<T> comparator)
{
HashSet<T> doops = new HashSet<T>(comparator);
return items.Where(p => !doops.Add(p)).Distinct(comparator);
}
public class ItemNameComparator : EqualityComparer<Item>
{
public override bool Equals(Item item1, Item item2)
{
return (item1 == null ? "" : item1.Name).ToUpperInvariant().Equals((item2 == null ? "" : item2.Name).ToUpperInvariant());
}
public override int GetHashCode(Item item)
{
return (item == null ? "" : item.Name).ToUpperInvariant().GetHashCode();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment