开发者

Copy Dictionary by value

开发者 https://www.devze.com 2022-12-17 17:54 出处:网络
How can i copy Dictionary object 开发者_如何学编程by value in c#Create a new Dictionary passing the source dictionary in the constructor (of course, this will not copy the objects in the dictionary if

How can i copy Dictionary object 开发者_如何学编程by value in c#


Create a new Dictionary passing the source dictionary in the constructor (of course, this will not copy the objects in the dictionary if they are reference types):

var copied = new Dictionary<KeyType, ValueType>(originalDictionary);


Using System.Linq;
Dictionary<int, string> dict2 = dict1.ToDictionary(k => k.Key, k => k.Value.ToString());

This will create an identical copy of a dictionary by value (not ref), so you can operate on one without changing the other.


There is no intrinsic method to do that. You'll have to do it manually.

The first step is to decide how deep you want the copy to pair. Do you want separate Dictionary entry object holding references to common keys & values, Or do you want everything copied. If the latter, they would need to implement ICloneable to create a general purpose method.

0

精彩评论

暂无评论...
验证码 换一张
取 消