Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!Contains() of List object doesn't work

Tags:

c#

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 goes to true even though MyObject is already in the list.

like image 806
Tony Avatar asked Mar 31 '10 20:03

Tony


People also ask

How do you use contains in a list of objects?

contains() is implemented by calling equals() on each object until one returns true . So one way to implement this is to override equals() but of course, you can only have one equals. Frameworks like Guava therefore use predicates for this. With Iterables.

How do I check if a list contains an object?

To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.

How list contains works in C#?

Contains: This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable(Of T). Equals method for T (the type of values in the list). This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

How do you check if an object contains a value in Java?

The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result.


2 Answers

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

like image 138
Etienne de Martel Avatar answered Oct 14 '22 08:10

Etienne de Martel


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.

like image 26
Anthony Pegram Avatar answered Oct 14 '22 08:10

Anthony Pegram