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?
2 Answers
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...
4 Comments
Bastardo
why not do
oldList = oldList.Distinct(customComparer).ToList();to avoid creating a new list Mr.Skeet?Is it bad?Wouldn't it work?Jonas Høgh
@JohnnyCageWins - that won't prevent creation of a new list, it will just overwrite the reference you held to the old one with a reference to the new one.
Bastardo
@Jonas H What?Seriously?I guess I imagined the memory flow very wrong for overwriting old list.I thought there would be no need for a creation if we use
oldList.Isn't there any way?Thanks Mr.H.Jon Skeet
@JohnnyCageWins: Yes, there's a big difference between declaring a new variable and creating a new object.
ToList always creates a new list. What you do with it afterwards is up to you.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);
}
}
}