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
andnovoAluno
? This data is coming from a database or a form?– Randrade
The code is a little weird, where is this
foreach
? That’s all different classes, right? Where did this one come fromnovoAluno
?– Maniero
@Randrade data comes from a form
– Amadeu Antunes
@New moustachAluno = new learnerAluno
– Amadeu Antunes
@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
@Randrade https://pastebin.com/LggbPegP
– Amadeu Antunes
That code is not what’s in the question.
– Maniero
@bigown https://pastebin.com/9yq8cpVj
– Amadeu Antunes
@Amadeuantunes Ever thought about doing the
where
in theforeach()
? Something likeforeach (var item in turmas.Where(t => t.nomeTurma == novoAluno.NomeTurma))
– Randrade
that would be more efficient ?
– Amadeu Antunes
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.
– Maniero
@bigown and instead of using the foreach could use the find ?
– Amadeu Antunes
I don’t see how, nor is searching there.
– Maniero
Why not use the
.Any
? https://answall.com/questions/32934/como-verificar-se-existe-um-elemento-dentro-de-uma-lista– mercador