Multi-tiered sorting using custom IComparer I have this custom IComparer I use to sort a list of SurveyResponse objects, but it seems really inefficient, both in terms of runtime performance, and code elegance and maintainability. I thought of implementing IComparable for each of these components, and each CompareTo knowing its "parent" to compare, but the sort order for this report I'm making won't necessarily be the same as other sort orders, so that may not work.

It looks like the sort of problem that should be solvable using recursion, but maybe I'm just over-analyzing it?

Are there any best practices that would make this faster and more maintainable?

private class CommentComparer : IComparer&lt;SurveyResponse&gt;
{
  public int Compare(SurveyResponse x, SurveyResponse y)
  {
    // Sort by Application Name...
    int result = x.Question.Survey.Feature.Application.Name.CompareTo(
      y.Question.Survey.Feature.Application.Name);
    if (result != 0) { return result; }
    // ...then Feature Name...
    result = x.Question.Survey.Feature.Name.CompareTo(
      y.Question.Survey.Feature.Name);
    if (result != 0) { return result; }
    // ...then SurveyTime...
    result = x.Question.Survey.TimeTaken.CompareTo(y.Question.Survey.TimeTaken);
    if (result != 0) { return result; }
    // ...then ID...
    result = x.Question.Survey.ID.CompareTo(y.Question.Survey.ID);
    if (result != 0) { return result; }
    // ...then Position.
    return x.Question.Position.CompareTo(y.Question.Position);
  }
}
You can use types from ComparerExtensions to make your code more maintainable:

IComparer&lt;SurveyResponse&gt; comparer = KeyComparer&lt;SurveyResponse&gt;
    .OrderBy(sr =&gt; sr.Question.Survey.Feature.Application.Name)
    .ThenBy(sr =&gt; sr.Question.Survey.Feature.Name)
    .ThenBy(sr =&gt; sr.Question.Survey.TimeTaken)
    .ThenBy(sr =&gt; sr.Question.Survey.ID)
    .ThenBy(sr =&gt; sr.Question.Position);


But I don't think you can actually make your comparer more efficient, it should be already very fast (it's just a few simple instructions). Are you sure your performance problem is caused by this comparer?