-1

I have two lists and I am trying to copy the source to the target. In the new iteration, changing the source affects the target. I understand, I am making a reference copy. Is there a way to make deep copy without using any serializer(due to performance issues). Please find my code below

public void ListFiller()
      {
         newListCopy = new List<KeyValuePair<string, object>>(newList);             
      } 
  • what are source and target lists? You want to change source values and copy all values of source to target? – raichiks Aug 02 '17 at 08:03
  • The Source is newList. And the target is newListCopy. I have to copy the newList into newListCopy and Input it into a dataGridView. For the next iteration the newList changes which changes the firstEntry of the dataGridview. That is the reason I need to copy the values not the reference – Sangathamilan Ravichandran Aug 02 '17 at 08:05
  • i would want the changes in newList in new iteration doesn't affect the newListCopy from last iteration – Sangathamilan Ravichandran Aug 02 '17 at 08:06

1 Answers1

1

The KeyValuePairs are structs and therefore will be recreated. However, the values of the KeyValuePair are not recreated because that are reference types. Therefore the same instance is still referenced in both data structures.

The performant way to solve that is to implement IClonable (or a custom clone method) and create a deep clone of your object manually. However that is time-consuming and you have to maintain the clone method if the object structure changes:

  public void ListFiller()
  {
     newListCopy = new List<KeyValuePair<string, object>>();
     foreach (var pair in newList)
     {
         var clone = (pair.Value as IClonable)?.Clone();
         // handle case that the object does not implement IClonable
         newListCopy.Add(new KeyValuePair<string, object>(pair.Key, clone );
     }           
  } 

As you already mentioned, a simpler way is, to use serialization for recreating the whole data structure. That is relativly easy to implement but not so performant (is that actually a problem?) and the objects need to be serializable.

The internet is full of similar questions and solutions.

JanDotNet
  • 3,746
  • 21
  • 30
  • Hi.. the object stucture is stable. And I have been using deep copy in earlier problems. I wanted to know whether there is a better solution. Let me try this and get back. Thanks. – Sangathamilan Ravichandran Aug 02 '17 at 08:22
  • 1
    I would add emphasis to "(is that actually a problem)". Usually hacks cost more than simple solutions. Do prefer simple to performance-optimized" unless you really have a performance problem. – Imre Pühvel Aug 02 '17 at 08:23