开发者

!Contains() of List object doesn't work

开发者 https://www.devze.com 2022-12-25 02:07 出处:网络
I am using Contains() to identify something that NOT contain in the list.So something like, if(!list.Contains(MyObject))

I am using Contains() to identify something that NOT contain in the list. So something like,

if(!list.Contains(MyObject))
{
//do something
}

but, the whole if statement g开发者_开发问答oes to true even though MyObject is already in the list.


What's the type of MyObject? Does it have a properly overriden Equals() method?


If you do not have the ability to override Equals (or if you just don't want to), you can implement an IEqualityComparer<T> of your object and pass that in as the second parameter to the Contains method (overload). If your object is a reference type, it would otherwise simply be comparing references instead of the contents of the object.

class Foo
{
    public string Blah { get; set; }
}

class FooComparer : IEqualityComparer<Foo>
{
    #region IEqualityComparer<Foo> Members

    public bool Equals(Foo x, Foo y)
    {
        return x.Blah.Equals(y.Blah);
    }

    public int GetHashCode(Foo obj)
    {
        return obj.Blah.GetHashCode();
    }

    #endregion
}

...

Foo foo = new Foo() { Blah = "Apple" };
Foo foo2 = new Foo() { Blah = "Apple" };

List<Foo> foos = new List<Foo>();

foos.Add(foo);
if (!foos.Contains(foo2, new FooComparer()))
    foos.Add(foo2);

In this scenario, foo2 would not be added to the list. It would without the comparer argument.


If you are testing to find an object in a List<T>, then the parameter in the Contains() method must be the same instance as the one in the list. It will not work if they are two separate but identical instances.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号