1

I have the following :

SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>>

that I want to deepcopy.

VolumeInfoItem is the following class :

[Serializable]
public class VolumeInfoItem
{
    public double up = 0;
    public double down = 0;
    public double neutral = 0;
    public int dailyBars = 0;

}

I have created the following Extension method :

public static T DeepClone<T>(this T a)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, a);
        stream.Position = 0;
        return (T)formatter.Deserialize(stream);
    }
}

I can't figure out how to get the deepCopy working ?

gevorg
  • 4,835
  • 4
  • 35
  • 52
user508945
  • 83
  • 1
  • 7
  • 2
    Please be more specific, I can't really tell what's your problem here. A quick tests shows that `DeepClone` works as intended. – Diadistis Nov 16 '10 at 01:13

1 Answers1

3

Your code looks like something in one of the answers of that question: How do you do a deep copy of an object in .NET (C# specifically)?

But, since you know the type of your dictionary's contents, can't you just do it manually?

// assuming dict is your original dictionary
var copy = new SortedDictionary<int, SortedDictionary<int, VolumeInfoItem>>();
foreach(var subDict in dict)
{
    var subCopy = new SortedDictionary<int, VolumeInfoItem>();
    foreach(var data in subDict.Value)
    {
        var item = new VolumeInfoItem
                   {
                       up = data.Value.up,
                       down = data.Value.down,
                       neutral = data.Value.neutral,
                       dailyBars = data.Value.dailyBars
                   };
        subCopy.Add(data.Key, item);
    } 
    copy.Add(subDict.Key, subCopy);
}

Compiled in my head, so a few syntax errors might have slipped by. It could also probably be made a bit more compact with some LINQ.

Community
  • 1
  • 1
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111