With regard to . Contains()
The method .Contains()
of List<T>
has a peculiarity that is to use the comparator returned by Equalitycomparer.default. According to the documentation:
The Default property checks if T implements the System.Iequatable interface and, if so, returns an Equalitycomparer that uses this implementation. Otherwise, it returns an Equalitycomparer that uses Object.Equals and Object.Gethashcode replacements provided by T.
That is, you can implement the interface IEqualityComparer<T>
in its class or override the method base.Equals()
and that will be the method of comparison used.
But why implement IEqualityComparer<T>
?
When you use the .Equals()
of the interface, there is a guarantee that the types of the original object and the object to be compared are equal. Not only does it make programming safer, it also has a slight impact on performance, since unlike base.Equals()
does not occur Boxing/Unboxing in comparison.
This scenario becomes more important when there is extensive use of comparisons where the costs of Boxing/Unboxing operation are no longer negligible.
Any Vs Contain
An interesting analysis is the comparison of complexities between the .Any()
and the .Contains()
.
The .Contains()
is an instance method and therefore complexity is dependent on the collection itself. In the case of a List<T>
complexity is O(n), while in a HashSet
complexity would be O(1).
Already the .Any()
is an extension whose complexity is always O(n), since it will go through the entire collection, apply the delegate passed to each element and return when find an element whose delegate returns true
.
Finally, the .Any()
due to the delegate, is more flexible than the .Contains()
which accepts only one object.
what are the attributes of Specificity?
– Tuyoshi Vinicius
I just edited the question Tuyoshi
– Rod