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<MyObject>.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? If so, I’d need to inherit something first, is that right?
List<T>.ContainsusesEqualityComparer<T>.Default, which in turn usesIEquatable<T>if the type implements it, orobject.Equalsotherwise.You could just implement
IEquatable<T>but it’s a good idea to overrideobject.Equalsif 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: