I'm trying to reorder a list using LINQ but seem to be getting quite confused. I imagine this is something simple but I can't seem to wrap my head around it.
I have the following setup using blazor:
@foreach (var question in Questions)
{
<div>
<p @onclick="@(() => MoveQuestionUp(question))">Move up</p>
<p @onclick="@(() => MoveQuestionDown(question))">Move down</p>
</div>
}
So very basic HTML just to click to reorder and move a question up and down a list.
public void MoveQuestionUp(Question question)
{
return MoveQuestion(question, "up");
}
public void MoveQuestionDown(Question question)
{
return MoveQuestion(question, "down");
}
public async Task MoveQuestion(Question question, string direction)
{
var currentOrder = question.Order;
var updatedOrder = direction == "up" ? currentOrder++ : currentOrder--;
// I'm unsure what to do at this point
// ...
await QuestionService.UpdateQuestionOrder(Questions);
}
I understand, I haven't attempted anything here because I'm utterly confused with what to do next. I understand the concept.
EDIT:
After feedback on a comment, I've update the MoveQuestion method, but I don't think it's optimal so would like to get opinions on it.
public async Task MoveQuestion(Question question, string direction)
{
var questionIndex = Questions.FindIndex(q => q.Id == question.Id);
if (questionIndex == 0 && direction="up")
{
return;
}
var targetQuestionIndex = direction == "up" ? questionIndex - 1 : questionIndex + 1;
var targetQuestion = Form.Questions[targetIndex];
(targetQuestion.Order, question.Order) = (question.Order, targetQuestion.Order);
await QuestionService.SaveChanges();
Questions = Questions.OrderBy(q => q.Order).ToList();
StateHasChanged();
}