2017-03-21 30 views
-1

我有一個包含2環的代碼:使用變量值作爲循環索引

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.

謝謝。

+2

前再次​​做迭代計算'+ = A-1'。 – dcg

+1

當你這樣做的時候,你在外層循環的條件(這已經足夠模糊了)中運行'IndexOutOfRangeException'的風險 – dlatikay

+0

有沒有任何選項可以避免它的交配? – Ben

回答

0

正如@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循環中的中間情況。希望能幫助到你。

0

首先

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 

}