c# - 使用 goto 突破 SUB-LOOPS
问题描述
我有三个嵌套循环。一旦最内层循环满足条件,我只想跳出最后两个嵌套循环(不是所有三个嵌套循环),然后继续父循环的下一项。
我不想返回或设置布尔检查。我只想看看这种方法是否可行。我有一个大数据,需要一些时间来确认。
while (all_Courses.Count != 0)
{
string drawnCourse = all_Courses[0];
foreach (Department department in departments)
{
if (department.Courses.Contains(drawnCourse))
{
foreach (DayOfWeek day in daySlot)
{
if (!department.Courses.Intersect(day.Day).Any())
{
day.Day[i] = drawnCourse;
all_Courses.Remove(drawnCourse);
goto NextCourse;
}
}
}
}
NextCourse:
continue; //start the iteration again at the parent loop
}
解决方案
如果您使用 Linq,您可能会更轻松地摆脱困境
使用 System.Linq;
然后,在您的部门循环中,应用一个内联 where 子句,以便它只抓取一个
foreach (Department department in
departments.Where( d => d.Courses.Contains( drawnCourse)).FirstOrDefault()
{
// now you will only get here for the first department that matches
// and will exit out after that. If no day match, it wont even try
// another department.
}
( d => .... ) 部分隐含为
当我在 WHERE 子句的括号内时,让变量“d”代表当前部门在列表中的任何内容。现在我可以比较它,一旦我到达第一个(或默认)记录,就可以继续。
应该只有一个部门可能会与一门课程相关联,然后会立即退出,甚至不会尝试第二个部门。
至于“allCourses”的外部循环,您可能需要从位置 0 开始通过索引进行迭代。如果从列表中删除课程,它显然会减少。但是现在,如果您删除您所在的课程,您不想增加计数,因为您的新“X”记录现在是 X+1 索引中的内容。小心你认为你是如何处理它们的。
推荐阅读
- javascript - 使用电子构建后,Sqlite3 5.0.2 无法正常工作
- binance - 如何以 USDT 作为数量参数创建订单?
- r - 如何从数据框创建边缘列表(展开,group_by?)
- javascript - 如何删除 message.channel.send?
- java - 在文件 I/O 期间获取 IndexOutOfBoundsException
- visual-studio-2019 - 在 Visual Studio 项目属性/代码分析选项卡中找不到“实时分析运行”复选框
- spring - How can i make my Spring Batch job to restart from a specific value in the database column?
- google-cloud-platform - GCP Data Loss Prevention API How to deindentify free text column in table
- java - Java/selenium : list.clear(); clearing the result that i was trying to store in map before clearing the list
- python - python nutrition log. Assigning multiple values to each key