Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you clone a dictionary in .NET?

I know that we should rather be using dictionaries as opposed to hashtables. I cannot find a way to clone the dictionary though. Even if casting it to ICollection which I do to get the SyncRoot, which I know is also frowned upon.

I am busy changing that now. Am I under the correct assumption that there is no way to implement any sort of cloning in a generic way which is why clone is not supported for dictionary?

like image 673
uriDium Avatar asked Feb 17 '10 09:02

uriDium


People also ask

How do I copy one dictionary to another?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

What is .NET dictionary?

Dictionary in . NET represents a collection of key/value pairs. In this tutorial, learn how to create a dictionary, add items to a dictionary, remove items from a dictionary, and other dictionary operations using C# and . NET. C# Dictionary class is a generic collection of keys and values pair of data.

Does C# have dictionary?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.


1 Answers

Use the Constructor that takes a Dictionary. See this example

var dict = new Dictionary<string, string>();  dict.Add("SO", "StackOverflow");  var secondDict = new Dictionary<string, string>(dict);  dict = null;  Console.WriteLine(secondDict["SO"]); 

And just for fun.. You can use LINQ! Which is a bit more Generic approach.

var secondDict = (from x in dict                   select x).ToDictionary(x => x.Key, x => x.Value); 

Edit

This should work well with Reference Types, I tried the following:

internal class User {     public int Id { get; set; }     public string Name { get; set; }     public User Parent { get; set; } } 

And the modified code from above

var dict = new Dictionary<string, User>();  dict.Add("First", new User      { Id = 1, Name = "Filip Ekberg", Parent = null });  dict.Add("Second", new User      { Id = 2, Name = "Test test", Parent = dict["First"] });  var secondDict = (from x in dict                   select x).ToDictionary(x => x.Key, x => x.Value);  dict.Clear();  dict = null;  Console.WriteLine(secondDict["First"].Name); 

Which outputs "Filip Ekberg".

like image 89
Filip Ekberg Avatar answered Oct 14 '22 08:10

Filip Ekberg