Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用变量值作为循环索引_C#_For Loop_Return - Fatal编程技术网

C# 使用变量值作为循环索引

C# 使用变量值作为循环索引,c#,for-loop,return,C#,For Loop,Return,我有一个包含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();

我有一个包含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;
        }
for(int count=0;list_Level[count]Math.Abs(x-初始值)x.TotalCost==LOpt_Temp.Max(y=>y.TotalCost));
添加(暂时[最佳利润]);
dataGridOpt.ItemsSource=LOpt;
}
我希望循环从0开始,但是,一旦内部循环第一次结束并以
a
值结束,我希望外部循环现在从这个位置开始

例如,第一个循环从0开始,内部循环在a=6时退出。现在我想从6开始计数,而不是1


谢谢。

如@dcg所述,在再次迭代之前,请先计算+=a-1。正如@dlatikay所提到的,您可能会遇到
indexootfrangeexception
。要避免这种情况,请在外部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(int count=0;list_Level[count]
请注意外部for循环中的中间条件。希望能有帮助。

首先

list_Level[count] < list_Level[list_Level.Count]
list\u Level[count]
通过使用此条件,您将获得您应该使用的IndexOutOfRangeException

list_Level[count] < list_Level[list_Level.Count - 1] 
list\u Level[count]
差不多吧。 另一方面,这可能有助于您:

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
for(int count=0;list_Level[count]=列表_Level.count)
{
打破
}
//你的代码

}

在再次迭代之前,请执行
count+=a-1
。执行此操作时,在外部循环的条件下(已经足够模糊),您将面临
索引自动失效异常的风险。是否有任何选项可以避免它匹配?