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;}
}