How do I stop "for" when I find an item in the list?

Asked

Viewed 74 times

3

I have the following code:

Console.Clear();
Console.Write("Nome da moto:");
string nomem = Console.ReadLine();
for (int i = 0; i < ListadeVeiculos.Count; i++)
{
      if (nomem == ListadeVeiculos[i].Nomemoto)
           Console.Write("Preço R$:" +ListadeVeiculos[i].Preco.ToString("0.00"));
      else Console.Write("Moto não cadastrada!");
}
Console.ReadKey();

Do you have a way to stop it when you find the element in the List?

In that my code if insert 2 elements in the list shows the message of if and of else.

  • Is that so? https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/break

2 answers

4


break closes the loop. see more about it in One should break into a?. The code would look better this way:

Write("Nome da moto:");
var nomeMoto = ReadLine();
var cadastrada = false;
foreach (var veiculo in ListaDeVeiculos) {
    if (nomeMoto == veiculo.NomeMoto) {
        Write($"Preço {veiculo.Preco:C");
        cadastrada = true;
        break;
    }
}
if (!cadastrada) Write("Moto não cadastrada!");

I put in the Github for future reference.

The impression is that the code has other problems.

  • Thanks! Managed to solve the problem

2

Browser other questions tagged

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