What is the most efficient way to place objects within a list contained in another object?

Asked

Viewed 46 times

0

     public turma(string nomeTurma)
     {
                this.nomeTurma = nomeTurma;
                listaAlunos = new List<aluno>();
      }   

      public aluno(string nomeAluno, string dataDeNascimento, string nomeTurma)
        {
            this.nomeAluno = nomeAluno;
            this.dataDeNascimento = dataDeNascimento;
            this.nomeTurma = nomeTurma;

        } 


     public  List<aluno> listaAlunos;

     foreach (var item in turmas)
      {
         if (item.nomeTurma == novoAluno.NomeTurma)
         {
            item.listaAlunos.Add(novoAluno);
         }
     }

I am placing students inside the listAlunos that is a property of the class object and for that I used a foreach where I check if the class that the student registered already exists created and if this exists I will put the student.

Is there any more efficient way to do this?

Do not understand the question comment below that I will improve the issue.

  • I could post how you’re filling out the data from turmas and novoAluno? This data is coming from a database or a form?

  • The code is a little weird, where is this foreach? That’s all different classes, right? Where did this one come from novoAluno?

  • @Randrade data comes from a form

  • @New moustachAluno = new learnerAluno

  • @Amadeuantunes I’m not sure I understand. Are you bringing the class list and the new student a form? While you’re at it, you could post the form code?

  • @Randrade https://pastebin.com/LggbPegP

  • That code is not what’s in the question.

  • @bigown https://pastebin.com/9yq8cpVj

  • 1

    @Amadeuantunes Ever thought about doing the where in the foreach()? Something like foreach (var item in turmas.Where(t => t.nomeTurma == novoAluno.NomeTurma))

  • that would be more efficient ?

  • 1

    But efficient is certainly not, is more concise, more declarative, needs to see what the goal is. It seems to me that more efficient than what you have done does not, unless the whole structure of the application can be changed, which should not even be the case. And if you need that efficiency, that’s another question.

  • @bigown and instead of using the foreach could use the find ?

  • I don’t see how, nor is searching there.

  • Why not use the .Any? https://answall.com/questions/32934/como-verificar-se-existe-um-elemento-dentro-de-uma-lista

Show 9 more comments
No answers

Browser other questions tagged

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