I have a strongly typed list of custom objects, MyObject, which has a property Id along with some other properties.
Let's say that the Id of a MyObject defines it as unique and I want to check if my collection doesn't already have a MyObject object that has an Id of 1 before I add my new MyObject to the collection.
I want to use if(!List.Contains(myObj)) but how do I enforce the fact that only one or two properties of MyObject define it as unique?
I can use IComparable? Or do I only have to override an Equals method but I'd need to inherit something first is that right?
Thanks
List<T>.Contains
usesEqualityComparer<T>.Default
, which in turn usesIEquatable<T>
if the type implements it, orobject.Equals
otherwise.You could just implement
IEquatable<T>
but it's a good idea to overrideobject.Equals
if you do so, and a very good idea to overrideGetHashCode()
if you do that:Note that the hash code relates to the criteria for equality. This is vital.
This also makes it applicable for any other case where equality, as defined by having the same ID, is useful. If you have a one-of requirement to check if a list has such an object, then I'd probably suggest just doing:
You can use LINQ to do this pretty easily.
List<T>
uses the comparer returned byEqualityComparer<T>.Default
and according to the documentation for that:So you can either implement
IEquatable<T>
on your custom class, or override theEquals
(andGetHashCode
) methods to do the comparison by the properties you require. Alternatively you could use linq:You can override Equals and GetHashCode, implement an
IEqualityComparer<MyObject>
and use that in theContains
call, or use an extension method likeAny
You can use
IEquatable<T>
. Implement this in your class, and then check to see if the T passed to the Equals has the same Id as this.Id. I'm sure this works for checking a key in a dictionary, but I've not used it for a collection.First define helper class with IEqualityComparer.
Then in your code, just define comparator and use it:
This way you can define the way how Equality is computed without modifying your classes. You can also use it for processing object from third party libraries as you cannot modify their code.