gpt4 book ai didi

c# - 如何在 while 循环中跳过多次迭代

转载 作者:行者123 更新时间:2023-11-30 19:39:55 24 4
gpt4 key购买 nike

我正在 While 循环中逐行读取文本文件。当我到达特定行时,我想跳过当前和接下来的 3 次迭代。

我想我可以使用计数器之类的东西来完成。但我想知道是否有更优雅的方式?

using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
// skip the next 3 iterations (lines)
}
}
}

最佳答案

有一个 for 循环来执行 sr.ReadLine 3 次并丢弃结果,如:

using (var sr = new StreamReader(source))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line == "Section 1-1")
{
for (int i = 0; i < 3; i++)
{
sr.ReadLine();
}
}
}
}

您应该检查 sr.ReadLine 返回 null 或者流是否已经结束。

关于c# - 如何在 while 循环中跳过多次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25691538/

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