Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> Sort uses Comparer<T> instead of IEquatable, Why?

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?

like image 769
Tony The Lion Avatar asked May 26 '11 12:05

Tony The Lion


4 Answers

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();
like image 116
Marc Gravell Avatar answered Nov 14 '22 22:11

Marc Gravell


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.

like image 41
Jon Skeet Avatar answered Nov 15 '22 00:11

Jon Skeet


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.

like image 33
SirViver Avatar answered Nov 15 '22 00:11

SirViver


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.

like image 4
dkackman Avatar answered Nov 15 '22 00:11

dkackman