Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> Where T is custom object. Remove duplicates by property

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.

like image 394
Pantelis Avatar asked Aug 20 '12 18:08

Pantelis


People also ask

How do you remove duplicates from an object in Python?

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.

Does converting set to list remove duplicates?

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.


1 Answers

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.

like image 102
Reed Copsey Avatar answered Nov 08 '22 08:11

Reed Copsey