I need to find and remove the duplicates from a List of tuples. Basically, my structure is made like that:
List> myList = new L
If you want a solution that amends the list in place, you can make use of a HashSet
(or for older frameworks a Dictionary
and ignore the value):
var existing = new HashSet>();
for (int i = myList.Count - 1; i >= 0; i--)
{
if (existing.Contains(myList[i]))
{
myList.RemoveAt(i);
}
else
{
existing.Add(myList[i]);
}
}
We count backwards without using an iterator (otherwise you'd get errors amending the list while iterating).
HashSet
also has overloads for overriding equality should you need it.
Personally I'd go for dasblinkenlight's answer for readability.