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.
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With