Resolve the usage of Continue external loops in internal loops
- 2020-05-10 18:42:42
- OfStack
Sometimes you want to perform Continue operations in an outer loop of a nested loop. For example, suppose you have a bunch of standards, and a bunch of items.
And you want to find an item that meets each criterion.
match = null;
foreach(var item in items)
{
foreach(var criterion in criteria)
{
if (!criterion.IsMetBy(item)) // If it doesn't meet the standard
{
// So that means that item It's definitely not looking, so it should be done in an outer loop continue operation
}
}
match = item;
break;
}
There are many ways to implement this requirement. Here are a few:
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 these criteria is not met, then goto OUTCONTINUE:, and then check 1 item.
Method #2(elegant, beautiful) :
When you see a nested loop, you can almost always consider putting the inner loop into one of its own methods:
match = null;
foreach(var item in items)
{
if (MeetsAllCriteria(item, critiera))
{
match = item;
break;
}
}
The inside of the MeetsAllCriteria method should obviously be
foreach(var criterion in criteria)
if (!criterion.IsMetBy(item))
return false;
return true;
Method #3, using the flag bit:
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, using 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 that all criteria are met.