I need to sort questions by its sort order.
One table named Questions stores the sort order info in QuestionId and SortOrder.
The other table ApplicantQuestions contains all the questions and answers, referencing the first table by QuestionId.
So basically we want to sort a list based on another list.
public class QuestionOrderComparer : IComparer<int>
{
private readonly IRepository<Question> _Questions;
public QuestionOrderComparer(IRepository<Question> Questions)
{
_Questions = Questions;
}
public int Compare(int x, int y)
{
var questionsInOrder = _Questions.All
.Select(q => new QuestionOrderModel(q.QuestionId, q.SortOrder))
.ToList();
var xValue = questionsInOrder.FirstOrDefault(q => q.Id == x)?.SortOrder ?? 0;
var yValue = questionsInOrder.FirstOrDefault(q => q.Id == y)?.SortOrder ?? 0;
return xValue - yValue;
}
}
That looks fine, but when I try to use it
thisSetOfApplicantQuestions
.OrderBy(x => x.QuestionId, new QuestionOrderComparer());
the intellisense requires me to add some parameter for IRepository<Question>
.
How to deal with that? Is it possible to have injection inside an IComparer
class?
What about hiding repository behind factory? Structure map will resolve everything for you.
Btw I wouldn't put this logic in a comparer unless you want to reuse it in many places. I always thought of using comparer in very simple cases without any external dependencies.