2014-10-06 39 views
0

能否告訴我如何將2維數組列表複製到另一個數組列表而不引用相同的數組實例?如何將2D數組列表複製到另一個

void partial_entropy(List<List<String>> class_lables)//This 2D "class_lables" arraylist contains many elements 
{ 
    List<List<String>> lables1 = new List<List<String>>(); 
    lables1 = class_lables; //copying old arraylist to new array list called "lables1" 
    //if I copy using the above method, both refer to same array instance. 

    //Therefore, I would like to use something like "CopyTo" method 
    class_lables.CopyTo(lables1, 0);//This did not work 

    for (int x = 0; x < lables1.Count; x++)//To print out the newly copyed 2D array 
    { 
      for (int y = 0; y < 1; y++) 
      { 
        Console.Write(lables1[x][y]+" "); 
        Console.WriteLine(lables1[x][y+1]); 
      } 
    } 
} 
+0

最壞的情況下,你可以通過class_lables循環,並添加項目lables1 – Gowtham 2014-10-06 06:12:51

回答

1
List<string> tempList=new List<string>(); 
foreach (List<String> lst in class_lables) 
{ 
    foreach (string str in lst) 
      tempList.Add(str); 
    lables1.Add(tempList); 
    tempList.Clear(); 
} 
+0

@DP。好。我編輯了答案。希望它解決了這個問題。否則,請告訴我你遇到錯誤的哪一行。 – 2014-10-06 05:54:09

+0

感謝您的更新。錯誤仍然發生在同一個地方:'Console.Write(lables1 [x] [y] +「」);'。錯誤說,「索引超出範圍。必須是非負值且小於集合的大小。「 – 2014-10-06 05:57:03

+0

@DP。總是使用'foreach'而不是'for'循環來防止這些錯誤。除此之外,它有效嗎? – 2014-10-06 06:00:37

相關問題