-1

how do you clone a dictionary such as this one :

Dictionary<int, List<User>>()

Every attempt that I make of cloning it ends up failing.

If I have this :

Dictionary<int, List<User>> dict1 = new Dictionary<int, List<User>>();
User user1=new User{Name="Mey"};
dict1.Add(1,user1);

doing this :

var dict2 = new Dictionary<int, List<User>>(dict1);

dict2 will still be referencing user1 instead of a new User object.

I want the User object to be duplicated so that changing the clone properties is not reflected on the original object.

Edit :

So I wrote the following code snippet :

        var dict2 = new Dictionary<int, List<User>>();

        //clone the dict1 dictionary
        foreach (var item in dict1)
        {
            var list = new List<User>();
            foreach (var u in item.Value)
            {
                list.Add(new User{ Name = u.Name, Total=u.Total}); 
            }
            dict2.Add(item.Key, list);
        }

     class User
     { 
        public string Name{get;set;}
        public double Total{get;set;}
     }
Attilah
  • 17,632
  • 38
  • 139
  • 202
  • hmmm... I mean a dictionary such as this one Dictionary> – Attilah Oct 24 '11 at 15:23
  • 2
    please show some source code... what have you tried ? What does "failing" mean ? Any error messages/exceptions ? – Yahia Oct 24 '11 at 15:24
  • I can't seem to enter this (Dictionary>) in the body of the question. :( – Attilah Oct 24 '11 at 15:24
  • See [this post](http://stackoverflow.com/questions/139592/what-is-the-best-way-to-clone-deep-copy-a-net-generic-dictionarystring-t) something similar was asked – Emmanuel N Oct 24 '11 at 15:26
  • You need to mark it as code by wraping it in `s. – SLaks Oct 24 '11 at 15:26
  • What do you want the List refer to? The exact same User objects (so changing the properties in the clones also changes the original) or a duplicate so that changing the clones won't change the original? – Martheen Oct 24 '11 at 15:28
  • @Martheen, I want a duplicate. changing the clone should not change the original. – Attilah Oct 24 '11 at 15:30

2 Answers2

3

.Net collections do not have built-in cloning support.

You need to create a new dictionary, loop through all of the entries in the original dictionary, add a corresponding entry with a new List<User> in the new dictionary, and loop through the original list to add copies of the User objects to the new list.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

You can use BinaryFormatter:

1) Serialize your object into a MemoryStream

therefore

2) Deserialize MemoryStream to a new object

Emanuele Greco
  • 12,551
  • 7
  • 51
  • 70
Aimeast
  • 1,609
  • 14
  • 29