2014-07-18 35 views
0

這裏是我的代碼:如何循環兩個列表後,如何在一次迭代後停止內循環?

List<int> myValues = new List<int>(new int[] { 5, 9, 3, 4, 7, 12, 0, 15 }); 
List<int> newOnly = new List<int>(new int[] { 5, 7, 1, 11, 7, 19, 76, 18 }); 
List<int> newValues = new List<int>(); 

for (int i = 0; i < myValues.Count; i++){ 
    for (int x = 0; x < newOnly.Count; x++){ 
     if (!myValues.Contains(newOnly[x])){ 
         newValues.Add(newOnly[x]); 
     } 
    } 
} 

我要檢查,如果在newOnly該項目在myValues已經存在一次。現在最後我得到newValues 40個項目,我應該只有9.

+0

要開始....爲什麼你迭代myValues而不只是newOnly? –

+4

刪除並且使用LINQ。 –

+0

查看「break」關鍵字:http://msdn.microsoft.com/en-us/library/adbctzc4.aspx – TyCobb

回答

0

我想你會需要更新,如果條件以確保您不添加到列表newValues重複引用:

for (int i = 0; i < myValues.Count; i++) 
     { 

      for (int x = 0; x < newOnly.Count; x++) 
      { 
       if (!myValues.Contains(newOnly[x]) && !newValues.Contains(newOnly[x])) 
       { 
        newValues.Add(newOnly[x]); 

       } 
      } 

     } 

當然,這可能不是最有效的方法,如無論如何,您將遍歷整個newOnly列表。

你可能想在每次迭代過myValuesnewValues做一個除了在newOnly,使你只迭代已經不在newValues

3

你不需要你的外循環,因爲你不是索引到任何地方的myValues。一個簡單的修復到當前的代碼如下:

for (int x = 0; x < newOnly.Count; x++){ 
    if (!myValues.Contains(newOnly[x])) 
     newValues.Add(newOnly[x]); 
} 

有更好的解決方案 - 如在使用LINQ將是一個不錯的選擇的評論中提到。

0

因爲別人已經回答瞭如何解決你的代碼的項目,這裏是一個回答您的如何阻止內環問題:

查找到關鍵字breakhttp://msdn.microsoft.com/en-us/library/adbctzc4.aspx

for (int i = 0; i < 10; i++) 
{ 
    for (int x = 0; x < 20; x++) 
    { 
     if (x == 5) 
      break; 
    } 
} 

如果if條件命中,它將退出內部for循環並返回到外部。