I am writing a for loop with multiple if statements.
Is it possible that if the if statement (or one part of it) in the for statement evaluates to false, then the loop does not exit but the integer to iterates increments by one and continues through the loop (I need functionality like the continue; keyword).
Example:
for (int i = 0; i <= Collection.Count && Collection[i].Name != "Alan"; i++)
{
// If name is not Alan, increment i and continue the loop.
}
Is this possible?
Thanks
You need functionality like the
continuekeyword – have you considered using thecontinuekeyword, then?Update: Your example code is hard to decipher the intention of.
The
forloop has three parts to it, separated by two semi-colons. The first part initializes the loop variable(s). The second part is an expression that is evaluated each time an iteration is about to start; if it is false, the loop terminates. The third part executes after each iteration.So your loop above will exit at the first “Alan” it encounters, and also it will increment
ievery time it finishes an iteration. Finally, if there are no Alans, it will execute the last time withiequal toCollection.Count, which is one larger than the maximum valid index into the collection. So it will throw an exception for sure, as you try to accessCollection[i]wheniis out of range.Maybe you want this:
You can think of the
Whereextension method as a way of filtering a collection.If this seems obscure, you can achieve the same thing with the
continuekeyword (as you guessed):Or you can just put the code in the
if‘s block: