首页 > 解决方案 > 使用 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

}

标签: c#

解决方案


如果您使用 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 索引中的内容。小心你认为你是如何处理它们的。


推荐阅读