I have written a whole bunch of objects that are all parts of collections and on which I will need to do lots of sort and search. On most of these object I have implemented and overridden the Equals
method, IEquatable
and operator!
and operator==
.
Now I come to wanting to use List<T>.Sort
on an object having implemented all above and it turns out I need to implement IComparable
to do custom sorting.
Why does Sort use IComparable
and what is then the point of having IEquatable
in all my objects?
Also what does Object.Equal
overriding have to do with all this?
It can't possibly use IEquatable<T>
to sort - knowing whether two things are equals doesn't help you rank them. However, it can use IComparable<T>
if your types implement it, or any IComparer<T>
(including Comparer<T>.Default
) to provide a custom comparer object. The functional style (Comparison<T>
) is convenient too, for ad-hoc sorting without lots of code:
list.Sort((x,y) => string.Compare(x.Name, y.Name));
but if you just want a simple ordinal sort, have your T
implement IComparable<T>
, and just use:
list.Sort();
Equality can only give you a result of whether two objects are equal or not. It can't tell you whether x
should come before or after y
in the sorted order. Given only equality, how would you propose that List<T>
should perform any sorting?
The point of implementing IEquatable<T>
is for when it's equality which is important, e.g. in HashSet<T>
or as the key type in a Dictionary<TKey, TValue>
. Likewise, those couldn't be implemented efficiently using only IComparable<T>
, as it wouldn't provide a hash code.
The two interfaces are basically used in different situations.
Because IComparable
allows to determine if an object is "smaller" or "bigger" than another object, whereas IEquatable
helps finding out whether two objects are "equal".
The former is needed for sorting, because just knowing which objects are of equal value doesn't help you putting them in a specific order.
Because sorting relies not on just equality but relative rank. In order to sort you need to know the position of objects relative to each other. Greater Than, Less Than, Equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With