patterncsharpMinor
Multi-tiered sorting using custom IComparer
Viewed 0 times
sortingtieredmultiicomparercustomusing
Problem
I have this custom
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?
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
{
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);
}
}Solution
You can use types from ComparerExtensions to make your code more maintainable:
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?
IComparer comparer = KeyComparer
.OrderBy(sr => sr.Question.Survey.Feature.Application.Name)
.ThenBy(sr => sr.Question.Survey.Feature.Name)
.ThenBy(sr => sr.Question.Survey.TimeTaken)
.ThenBy(sr => sr.Question.Survey.ID)
.ThenBy(sr => 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?
Code Snippets
IComparer<SurveyResponse> comparer = KeyComparer<SurveyResponse>
.OrderBy(sr => sr.Question.Survey.Feature.Application.Name)
.ThenBy(sr => sr.Question.Survey.Feature.Name)
.ThenBy(sr => sr.Question.Survey.TimeTaken)
.ThenBy(sr => sr.Question.Survey.ID)
.ThenBy(sr => sr.Question.Position);Context
StackExchange Code Review Q#12221, answer score: 8
Revisions (0)
No revisions yet.