John Pietrar John Pietrar - 13 days ago 6
C# Question

After matching first found occurrence stop reading

I have something like :

string lines = "yes no \nmaybe no"


foreach (string line in lines)
{
if (line.Contains("no"))
{
//do whatever here
}
}


I want it to stop reading after the first
no
occurrence.Should I use something else instead of
Contains
? Or is there a way to solve it how it is?

Answer

For an alternative, you can also use the break; keyword. This will allow you to exit a loop, and in your case once a condition is met.

string lines = "yes no \nmaybe no"

foreach (string line in lines)
        {
            if (line.Contains("no"))
               {
                 // condition is met, let's exit the foreach loop
                 break;
               }
        }