Food list gives "Index out of range"

Asked

Viewed 106 times

3

In my system, I need to return to the number of questions that the student missed on a particular topic. To achieve this, I tried creating a class that has two attributes: Tema and QteErros and installed her in my controller.

public ActionResult errosPorTema(int idAluno)
{
   Aluno a = alunoModel.obterAluno(idAluno);
   List<Tema> temasalunoAtividadeModel.listarTemasPorAluno(idAluno);

   List<ErradaTema> listaErradasTema = new List<ErradaTema>();

   for (int i = 0; i < temas.Count; i++)
   {
      int idTema = temas[i].idTema;
      int qtdErros =      alunoAtividadeModel.listarPerguntasErradasPorTema2(a.idAluno, idTema);

      listaErradasTema[i].Tema = temas[i].Descricao;
      listaErradasTema[i].QtdErradas = qtdErros;
    }

    return View(listaErradasTema);
}

The class ErradaTema:

public class ErradaTema
    {
        public string Tema { get; set; }
        public int QtdErradas { get; set; }

        public ErradaTema(string tema, int qtdErradas)
        {
            this.Tema = tema;
            this.QtdErradas = qtdErradas;
        }

        public ErradaTema()
        {

        }

    }

The problem is on the lines listaErradasTema[i].Tema = temas[i].Descricao; and listaErradasTema[i].QtdErradas = qtdErros;.

  • If you put the code instead of image and how is the class ErradaTema I can improve the answer and try to see if there is something else wrong.

  • Ok. I will edit the question with the code, and show the Eradicate class

  • [Edit] the question.

1 answer

4


The error is that you are not adding an element to the new list. You cannot access the element without creating it first. nor do you actually need to access it:

public ActionResult errosPorTema(int idAluno) {
    Aluno a = alunoModel.obterAluno(idAluno);
    List<Tema> temas = alunoAtividadeModel.listarTemasPorAluno(idAluno);
    var listaErradasTema = new List<ErradaTema>();
    for (int i = 0; i < temas.Count; i++) {
        listaErradasTema.Add(new ErradaTema() {
            Tema = temas[i].Descricao,
            QtdeErradas = alunoAtividadeModel.listarPerguntasErradasPorTema2(a.idAluno, temas[i].idTema)
        });
    }
    return View(listaErradasTema);
}

I put in the Github for future reference.

See more in Why it occurs and how to resolve an error of "out of Bounds" or "out of range" or something of type?.

Since the class has a constructor with both properties, it could initialize with it. But I doubt this builder is necessary. The other constructor is certainly not necessary. I would simplify this class and leave only the properties. Unless it will grow.

  • Thank you very much Bigown! was that right.

  • I made a hit because after editing it was what gave to check the code better.

  • Vlw! helped me a lot!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.