2013-01-01 89 views
-1

我創建了列表列表來存儲隨機生成的數據,但是我的實現顯示以下intellisense錯誤「變量名稱在當前上下文中不存在」。我哪裏錯了?這是我的代碼所需的部分。列表訪問列表

  List<List<string>> DataList = new List<List<string>>(); 
      //Some Code 
      for (int i = 0; i < num; i++) 
      { 
       List<string> strVal = new List<string>(); 
       foreach (string someVal in SomeList) 
       {      
        //Some Code 
        strVal.Add(data); 
       } 

       DataList.Add(strVal); 
      } 

      for (int i = 0; i < num; i++) 
      { 
       foreach (IList<string> name in DataList) 
       { 
        foreach (string listVal in strVal) // Error Here 
        { 
         //Some Code 
        }      
       } 
      } 

我哪裏出錯了?謝謝。

回答

2
foreach (IList<string> name in DataList) 
      { 
       foreach (string listVal in strVal) // Error Here 
       { 
        //So 

應該

foreach (IList<string> name in DataList) 
      { 
       foreach (string listVal in name) // Error Here 
       { 
        //So 
+0

謝謝。有我的錯誤。 –

2

您正在定義strVal裏面第一個for循環,並試圖訪問它在第二個。

strVal在第一個for循環結束時超出範圍。在第一個循環之外定義它,以便它可以被兩個循環訪問。

List<List<string>> DataList = new List<List<string>>(); 
//Some Code 
List<string> strVal = new List<string>(); 
for (int i = 0; i < num; i++) 
{   
    foreach (string someVal in SomeList) 
    {      
     //Some Code 
     strVal.Add(data); 
    } 
    DataList.Add(strVal); 
} 
for (int i = 0; i < num; i++) 
{ 
    foreach (IList<string> name in DataList) 
    { 
     foreach (string listVal in strVal) 
     { 
      //Some Code 
     }      
    } 
} 

這是什麼導致你的錯誤,雖然它可能不是你想要做的。見@Chen的回答一些更合理的:)

+0

感謝您的解釋。 –