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.
source
share