如何打破2路无在C#标志变量? [英] How to break out of 2 loops without a flag variable in C#?

查看:79
本文介绍了如何打破2路无在C#标志变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个简单的例子可以说我有以下电网和我正在寻找一个特定的单元格值。当发现我不再需要处理循环。

As a trivial example lets say I have the following grid and I am looking for a particular cells value. When found I no longer need to process the loops.

foreach(DataGridViewRow row in grid.Rows)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        if(cell.Value == myValue)
        {
            //Do Something useful
            //break out of both foreach loops.
        }
    }
}

这是如何在C#中完成的。在Java中,我可以使用标签来命名最外层循环,然后打破这个循环,但我似乎无法找到在C#中equivelant。

How is this done in C#. In Java I could use a label to name the outermost loop, and then break that loop, but I can't seem to find an equivelant in C#.

什么是C#实现这个的tersest方式吗?我知道我可以设置一个布尔标志,并检查它在外环打出来的那一个为好,但它只是似乎过于冗长。

What is the tersest way of accomplishing this in c#? I know I can set a boolean flag, and check it in the outer loop to break out of that one as well, but it just seems too verbose.

谢谢,

推荐答案

最愉快的方式就是出打破了第二个循环到一个函数,就像这样:

The most pleasant way is to break the second loop out into a function, like this:

public void DoubleLoop()
{
    for(int i = 0; i < width; i++)
    {
        for(int j = 0; j < height; j++)
        {
            if(whatever[i][j]) break; // let's make this a "double" break
        }
    }
}

进入

public bool CheckWhatever(int whateverIndex)
{
    for(int j = 0; j < height; j++)
    {
        if(whatever[whateverIndex][j]) return false;
    }

    return true;
}

public void DoubleLoop()
{
    for(int i = 0; i < width; i++)
    {
        if(!CheckWhatever(i)) break;
    }
}

当然,随时与LINQ或简化这个什么(你可以把 CheckWhatever 进入死循环状态了。)这是原则只是一个详细的演示

Of course, feel free to simplify this with LINQ or whatever (you could put CheckWhatever into the loop condition, too.) This is just a verbose demonstration of the principle.

这篇关于如何打破2路无在C#标志变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆