Reputation: 1061
I need a C# method to remove duplicates from a List<T>
using a custom comparison operation. In .NET 4. Is there one or do I have to write it myself?
Upvotes: 2
Views: 1780
Reputation: 128317
You could go with Jon's answer, or if you really want to remove duplicates from an existing list, something like this would work:
public static void RemoveDuplicates<T>(this IList<T> list, IEqualityComparer<T> comparer = null)
{
comparer = comparer ?? EqualityComparer<T>.Default;
var uniques = new HashSet<T>(comparer);
for (int i = list.Count - 1; i >= 0; --i)
{
if (!uniques.Add(list[i]))
{
list.RemoveAt(i);
}
}
}
Upvotes: 6
Reputation: 1500385
Assuming your comparison operation is IEqualityComparer<T>
or can be converted to it, you're fine with LINQ:
var newList = oldList.Distinct(customComparer).ToList();
Obviously that creates a new list rather than removing elements from the old one, but in most cases that's okay. You could always completely replace the contents of the old list with the new list afterwards if not...
Upvotes: 7