How do i make sure that List<T>.Contains(T) works with my custom class?

跟風遠走 提交于 2019-12-14 04:17:07

问题


I use .net 2.0 (C#)

I have a Person class, and i pupulate List< Person> p from the database.

i know for a fact that my list has duplicates, but when i try to remove the duplicates they don't get removed.

Does my Person class need to implement any interfaces for List< T>.Contains(T) to work properly?

Any other ideas?

Thank you.


回答1:


Your Person class should implement IEquatable




回答2:


You should override Equals and GetHashCode method.




回答3:


The example you reference is not a solution for removing dupes from a list, it is a function that takes a list and yields an iterator that will exclude duplicates. If you need to dedupe the entire list in one go you would need to take the IEnumerable<T> returned from the function and pass it into a new List<T>.




回答4:


You need to overload Object.Equals(Object obj) in your class.




回答5:


The docs say "This method determines equality using the default equality comparer EqualityComparer(T).Default".



来源:https://stackoverflow.com/questions/593171/how-do-i-make-sure-that-listt-containst-works-with-my-custom-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!