! Contains () of List object not working

I use Contains()to determine what is NOT in the list. So something like

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

but the entire if statement is true, although it is MyObjectalready in the list.

+5
source share
3 answers

If you cannot override Equals (or if you do not want to), you can implement IEqualityComparer<T>your object and pass this as the second parameter to the Contains method (overload). If your object is a reference type, otherwise it would just be a comparison of links instead 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 case, foo2 will not be added to the list. That would be without a comparison argument.

+3
source

MyObject? Equals()?

+9

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

+1
source

All Articles