Modify List.Contains behavior

╄→гoц情女王★ 提交于 2019-12-04 00:57:30

问题


I have a List<MyObj> with the class MyObj : IComparable. I wrote the method CompareTo in the MyObj class per the IComparable interface, but when I use the List<MyObj>.Contains(myObjInstance) it returns false when it should be true.

I'm not sure I'm understanding how I need to proceed to make sure the List uses my custom comparison method when calling then Contains function.

Here is my compareTo implementation:

    #region IComparable Members

    public int CompareTo(object obj)
    {
        MyObj myObj = (MyObj)obj;
        return String.Compare(this.Symbol, myObj.Symbol, true);
    }

    #endregion

Note the Symbol property is a string.

To clarify I've put a stopping point in that compareTo method and it doesn't even go in there.

Anyone has ever tried that?

Thanks.


回答1:


The absolute easiest way to find out whether your CompareTo method is called is to set a breakpoint in it and hit F5 to run your program. But I believe that List<T>.Contains looks for the IEquatable<T> interface for making the comparison.




回答2:


According to the documentation for List<T>.Contains, it uses either your implementation of IEquatable interface or object.Equals, that you can override as well.




回答3:


Did you try overriding the Equals method?

List<T>, according to reflector, uses EqualityComparer<T> to check for containment, and the default implementation (ObjectEqualityComparer) uses Equals for most normal objects.



来源:https://stackoverflow.com/questions/1076350/modify-list-contains-behavior

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