[英]2D array of dictionaries - copying
Lets tell i've got 2D array of dictionaries:让我们告诉我有字典的二维数组:
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>() }
}
And i need to copy this to another.我需要将其复制到另一个。 I tried all ways.
我尝试了所有方法。
Something like:就像是:
matNew = mat;
But still when i change the first one, ,it automatically change the second one.但是当我改变第一个时,它会自动改变第二个。
I really don't know how to do this.我真的不知道该怎么做。
I assume you want a deep copy?我假设你想要一个深拷贝?
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]);
The Dictionary(IDictionary<TKey, TValue>)
constructor copies all elements from the specified dictionary, and is probably the fastest way of performing a shallow clone of an existing dictionary. Dictionary(IDictionary<TKey, TValue>)
构造函数复制指定字典中的所有元素,这可能是对现有字典执行浅表克隆的最快方法。 This is suitable for your case, since your keys and values are both immutable ( int
and string
).这适合您的情况,因为您的键和值都是不可变的(
int
和string
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.