2012-04-06 125 views
0

讓告訴我有字典的二維數組:字典的二維數組 - 複製

public Dictionary<int, string>[,] mat = new Dictionary<int, string>[3, 5] 
{ 
    { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() }, 
    { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() }, 
    { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() }, 
    { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() },   
    { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() } 
} 

,我需要複製這到另一個。我嘗試了各種方法。
喜歡的東西:

matNew = mat; 

但仍當我改變的第一個,它會自動更改第二個。
我真的不知道該怎麼做。

+0

一個變化,另一個變化,所以你說你想要一個深層複製呢? – payo 2012-04-06 17:50:57

+0

@payo - 確實如此。 – 2012-04-06 17:55:09

+0

數組是參考類型; 「mat」只是對實例的引用,「matNew = mat」複製引用,而不是實際的數組。你正在試圖創建一個數組的副本,還是數組的副本以及它中的所有字典? – 2012-04-06 17:57:10

回答

2

我假設你想要一個深層複製?

var matNew = new Dictionary<int, string>[mat.GetLength(0), mat.GetLength(1)]; 
for (int i = 0; i < mat.GetLength(0); ++i) 
    for (int j = 0; j < mat.GetLength(1); ++j) 
     matNew[i, j] = new Dictionary<int, string>(mat[i, j]); 

Dictionary(IDictionary<TKey, TValue>)拷貝構造函數從指定的字典中的所有元素,可能是執行現有的字典的淺表副本的最快方法。這適用於您的情況,因爲您的密鑰和值都是不可變的(intstring)。