Reorder a list of items and update in the database

Viewed 109

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();
}
1 Answers
public async Task MoveQuestionUp(Question question)
{
    var questionIndex = Questions.FindIndex(q => q.Id == question.Id);

    if(questionIndex == 0)
    {
        return;
    }
    
    var previousQuestion = Questions[questionIndex - 1];
    
    await SwapOrder(question, previousQuestion);

}

public async Task MoveQuestionDown(Question question)
{
    var questionIndex = Questions.FindIndex(q => q.Id == question.Id);

    if(questionIndex == Questions.Count - 1) // last question
    {
        return;
    }

    var nextQuestion = Questions[questionIndex + 1];

    await SwapOrder(question, nextQuestion)
}

private async Task SwapOrder(Question a, Question b)
{
    var temp = a.Order;
    a.Order = b.Order;
    b.Order = temp;
    
    await QuestionService.SaveChanges();

    Questions = Questions.OrderBy(q => q.Order).ToList();
}
Related