I have a List<T>
where T is a custom object. None of my object are equal but some might have an equal property. Is there any fast way to remove the duplicates by comparing the property? It doesn't matter which of the duplicates stays in the list.
If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.
Using set Therefore, converting a list into a set removes the duplicates. Changing the set into a list yields a new list without duplicates. The following example shows how to remove duplicates from the students list using set . Notice that the order of the elements in the list is different from our previous examples.
You can use List<T>.RemoveAll
to do this efficiently.
For example, if you wanted to remove all elements where the Foo
property had a value of 42, you could do:
theList.RemoveAll(i => i.Foo == 42);
If you're trying to make a list of distinct items by a property, ie: keep only distinct Foo items, I would recommend doing something like:
HashSet<int> elements = new HashSet<int>(); // Type of property
theList.RemoveAll(i => !elements.Add(i.Foo));
This will track which elements are "distinct" and remove all others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With