How can I make a deep-copy of a read only OrderedDictionary with keys and values being strings that is no longer read only?

删除回忆录丶 提交于 2019-12-11 23:28:42

问题


The orderedDictionary instantiation is this:

IOrderedDictionary orderedDictionary= gridview.DataKeys[index].Values;

orderedDictionary is read only.

How can I make a deep copy of orderedDictionary that is not read only? Serialization/deserialization doesn't work cause it also copies the read only part.


回答1:


The easiest way would be to just copy the objects:

var newDictionary = new OrderedDictionary();
foreach(DictionaryEntry de in orderedDictionary)
{
    newDictionary.Add(de.Key, de.Value);
}

UPDATE:
This code will NOT create a deep copy of the values in the dictionary.
Example:

var orderedDictionary = new OrderedDictionary();
orderedDictionary.Add("1", new List<int> { 1, 2 });

var newDictionary = new OrderedDictionary();
foreach(DictionaryEntry de in orderedDictionary)
{
    newDictionary.Add(de.Key, de.Value);
}

Both dictionary will contain one entry with the key "1" and the same list. Removing an item from this list in any of the dictionaries will also change the contents of the list in the other dictionary, because there only IS one list.

Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);
Console.WriteLine(ReferenceEquals(orderedDictionary["1"], newDictionary["1"]));
((List<int>)orderedDictionary["1"]).Remove(1);
Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);

This will output the following:

2
2
True
1
1

Assigning a new value to a key in one of the dictionary however has no effect on the other dictionary:

newDictionary["1"] = new List<int>{3,4};
Console.WriteLine(ReferenceEquals(orderedDictionary["1"], newDictionary["1"]));
Console.WriteLine(((List<int>)orderedDictionary["1"]).Count);
Console.WriteLine(((List<int>)newDictionary["1"]).Count);

This will output:

False
2
3


来源:https://stackoverflow.com/questions/6621943/how-can-i-make-a-deep-copy-of-a-read-only-ordereddictionary-with-keys-and-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!