I have a collection of user defined class object, e.g. Car instances, what is the best way to sort it.
Below are the possible ways, which one is the best, is there other ways?
- IComparable
- Comparer
- Comparison
- IEquatable
Any idea would be very much appreciated
There’s another important and extremely simple way, unless you absolutely require that you sort in-place: use LINQ to Objects. For example:
You can order by multiple projections, and in a varied fashion, like this:
I’ve only put the
ToListat the end to create aList<Car>at the end – if you only need to iterate over the results though, you can let it perform the ordering lazily:Personally I find this the most flexible way of sorting. Otherwise, using
IComparer<T>andComparison<T>are the next most flexible, as anyone can order that way.IComparable<T>requires the class itself to decide how items are going to be ordered, and you can only implement it once, which makes it somewhat inflexible.IEquatable<T>is used for comparing items for equality, so is used for things likeHashSet<T>, not for ordering.