These statements are usually used together with conditional statements.
When a continue is encountered in a loop, the loop is terminated without executing any statement next to the continue in the loop.
The continue statement ends the current loop and enters the next loop.
For (var I = 1; I <= 10; I ++)
{
If (I = 6) continue;
Document. write (I );
}
// Output result: 1234578910
The continue statement can only be used in the loop body of the while statement, do/while statement, for statement, or for/in statement. It may cause errors when used elsewhere!
Sometimes you want to perform the Continue operation in the outer loop of a nested loop. For example, suppose you have a series of standards and a bunch of items. And you want to find an item that meets every standard. Match = null;
Foreach (var item in items)
{
Foreach (var criterion in criteria)
{
If (! Criterion. IsMetBy (item) // if the criteria are not met
{
// This indicates that this item is definitely not to be searched, so the continue operation should be performed in the outer loop.
}
}
Match = item;
Break;
}
There are many ways to achieve this. Here are some: Method #1 (ugly goto): Use the goto statement.
Match = null;
Foreach (var item in items)
{
Foreach (var criterion in criteria)
{
If (! Criterion. IsMetBy (item ))
{
Goto OUTERCONTINUE;
}
}
Match = item;
Break;
OUTERCONTINUE:
;
} If one of the criteria is not met, go to OUTCONTINUE:, and then check the next item. Method #2 (elegant and beautiful ):
When you see a nested loop, basically you can always consider putting the internal loop into one of its own methods: match = null;
Foreach (var item in items)
{
If (MeetsAllCriteria (item, critiera ))
{
Match = item;
Break;
}
} The internal content of the MeetsAllCriteria method is obviously
Foreach (var criterion in criteria)
If (! Criterion. IsMetBy (item ))
Return false;
Return true;
Method #3, use the flag:
Match = null;
Foreach (var item in items)
{
Foreach (var criterion in criteria)
{
HasMatch = true;
If (! Criterion. IsMetBy (item ))
{
// No point in checking anything further; this is not
// A match. We want to "continue" the outer loop. How?
HasMatch = false;
Break;
}
}
If (HasMatch ){
Match = item;
Break;
}
}
Method #4: Use Linq.
Var matches = from item in items
Where criteria. All (
Criterion => criterion. IsMetBy (item ))
Select item;
Match = matches. FirstOrDefault (); for each item in items, check whether all criteria are met
Instance
LstFor. Items. Clear ();
// For loop
For (int I = 1; I <11; I ++)
{
LstFor. Items. Add (I. ToString ());
}
LstForeach. Items. Clear ();
// Foreach loop
Foreach (ListItem item in lstFor. Items)
{
If (int. Parse (item. Value) % 2 = 0)
{
LstForeach. Items. Add (item );
}
}