Is it possible, and if so how do I override the Contains
method of an otherwise normal List<T>
, where T
is my own, custom type?
views:
1324answers:
5You need to override Equals
and GetHashCode
in your class (MyType
).
If you implement the equals of you custom type, the contains function of List will work
To make your own Contains implementation you could create a class that implements the IList interface. That way your class will look like a IList. You could have a real List internally to do the standard stuff.
class MyTypeList : IList<MyType>
{
private List<MyType> internalList = new ...;
public bool Contains(MyType instance)
{
}
....
}
List<T>
uses EqualityComparer<T>.Default
to do comparisons; this checks first to see if your object implements IEquatable<T>
; otherwise is uses object.Equals
.
So; the easiest thing to do is to override Equals
(always update GetHashCode
to match the logic in Equals
). Alternatively, use LINQ instead:
bool hasValue = list.Any(x => x.Foo == someValue);
Depending on what specific needs you have in your override you might use Linq expression for doing that:
list.Any(x => x.Name.Equals("asdas", .....)) // whatever comparison you need
You can then wrap it in an extension method for convenience.