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

2

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();

Is there any way to stop when you find the element in the List?

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

    
asked by anonymous 19.05.2018 / 21:07

2 answers

3

break terminates the loop. see more about it at Should I use break in for? . 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!");

The impression is that the code has other problems.

    
19.05.2018 / 21:16
2

There is the break statement that ends a loop.

var motos = new List<string>
{
    "MotoA",
    "MotoB",
    "MotoC",
    "MotoD"
};

foreach (var moto in motos)
{
    if (moto.Equals("MotoC"))
    {
        break;
    }
 }

More about the break statement

link

    
19.05.2018 / 21:17