我有一个包含 2 个 for 循环的代码:
for (int count = 0; list_Level[count] < list_Level[list_Level.Count]; count++)
{
for (int a = 0; list_Level[a] < Initial_Lvl; a++)
{
var dOpt = new DataGridObjectOpt();
double Closest_Goallvl = list_Level.Aggregate((x, y) => Math.Abs(x - Initial_Lvl) < Math.Abs(y - Initial_Lvl) ? x : y);
dOpt.ImageSource = new Uri(filePaths[a], UriKind.RelativeOrAbsolute);
dOpt.Level_Index = Initial_Lvl;
dOpt.Level_Goal = goallvl;
dOpt.Stage = 1;
LOpt_Temp.Add(dOpt);
}
count = a;
int best_Profit_Ind = LOpt_Temp.FindIndex(x => x.TotalCost == LOpt_Temp.Max(y => y.TotalCost));
LOpt.Add(LOpt_Temp[best_Profit_Ind]);
dataGridOpt.ItemsSource = LOpt;
}
我希望循环从 0 开始,但是一旦内部循环第一次结束并以 a
的值结束,我希望外部循环现在从这个地方开始。
例如,第一个循环从 0 开始,内部循环在 a=6 时退出。现在我希望计数从 6 而不是 1 开始。
谢谢。
正如@dcg提到的,在再次迭代之前,请计数+=a-1。正如@dlatikay提到的,您可能会遇到IndexOutOfRangeException
。为避免这种情况,请在外部 for 循环中添加和条件。因此,最终代码如下所示:
for (int count = 0; list_Level[count] < list_Level[list_Level.Count] && count < list_Level.Count; count++)
{
for (int a = 0; list_Level[a] < Initial_Lvl; a++)
{
//Your code
}
count+=a-1
//Your code
}
请注意外部 for 循环中的中间条件。希望对您有所帮助。
首先
list_Level[count] < list_Level[list_Level.Count]
通过使用这个条件,你将得到你应该使用的IndexOutOfRangeException。
list_Level[count] < list_Level[list_Level.Count - 1]
类似的东西。另一方面,这可能有助于您:
for (int count = 0; list_Level[count] < list_Level[list_Level.Count - 1] && count < list_Level.Count; count++){
for (int a = 0; list_Level[a] < Initial_Lvl; a++)
{
//Your code
}
count = a-1;
if(count >= list_Level.Count)
{
break;
}
//Your code
}