gpt4 book ai didi

c# - 如何在 C# 中没有标志变量的情况下跳出 2 个循环?

转载 作者:IT王子 更新时间:2023-10-29 03:57:49 26 4
gpt4 key购买 nike

作为一个简单的例子,假设我有以下网格并且我正在寻找特定的单元格值。发现后我不再需要处理循环。

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# 中找到等效项。

在 C# 中完成此任务的最简洁方法是什么?我知道我可以设置一个 bool 标志,并在外循环中检查它以跳出那个循环,但它看起来太冗长了。

谢谢,

最佳答案

1

foreach(DataGridViewRow row in grid.Rows)
foreach(DataGridView cell in row.Cells)
if (cell.Value == somevalue) {
// do stuff
goto End;
}
End:
// more stuff

2

void Loop(grid) {
foreach(row in grid.Rows)
foreach(cell in row.Cells)
if (something) {
// do stuff
return;
}
}

3

var cell = (from row in grid.Rows.OfType<DataGridViewRow>()
from cell in row.Cells.OfType<DataGridViewCell>()
where cell.Value == somevalue
select cell
).FirstOrDefault();

if (cell != null) {
// do stuff
}

关于c# - 如何在 C# 中没有标志变量的情况下跳出 2 个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/982595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com