2

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?

  1. IComparable
  2. Comparer
  3. Comparison
  4. IEquatable

Any idea would be very much appreciated

1 Answer 1

11

There's another important and extremely simple way, unless you absolutely require that you sort in-place: use LINQ to Objects. For example:

var orderedByName = cars.OrderBy(car => car.Name).ToList();

You can order by multiple projections, and in a varied fashion, like this:

var complex = cars.OrderByDescending(car => car.Year)
                  .ThenBy(car => car.Model)
                  .ThenByDescending(car => car.Make)
                  .ToList();

I've only put the ToList at the end to create a List<Car> at the end - if you only need to iterate over the results though, you can let it perform the ordering lazily:

var query = cars.OrderByDescending(car => car.Year)
                  .ThenBy(car => car.Model)
                  .ThenByDescending(car => car.Make);

foreach (var car in cars)
{
    // Use car
}

Personally I find this the most flexible way of sorting. Otherwise, using IComparer<T> and Comparison<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 like HashSet<T>, not for ordering.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your advice, which solifies my understanding.
@John, THis is off the topic. I read both version of your books, c# in depth. What c# book would you recommend, apart from your books, for a c# expert. How to apply for a Software Engineer in Google?
@Pingpong: Actual C# language books? The specification, ideally... if you've understood C# in Depth, there aren't any books I know of that go into more language detail. CLR via C# and C# 4 in a Nutshell go into lots of depth on other fronts, mind you. As for applying to Google - ping my your CV at [email protected].
@John, both CLR via C# and C# 4 in a Nutshell are great books, as is C# in depth. I will do that at [email protected].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.