0

I have a list of lists that I need to "copy" and do some modification on the copied object. However, the updates that I'm doing on the target object seems to be updating the source object as well because of the reference.

I'm aware in order to "clone" my source list I have to do .ToList(). However, this is not working in my case. All I want is to update my target without affecting the source. Any help is greatly appreciated

static void Main(string[] args)
{
    List<List<string>> list = new List<List<string>>();
    list.Add(new List<string> { "abc", "def" });
    
    CreateList(list);
}

static void CreateList(List<List<string>> original)
{
    List<List<string>> temp = original;
    temp.ToList();

    foreach (var row in temp)
    {
        row.Add("zzz"); //this adds it in the "original" object as well along with "temp"
    }
}
Abhilash V
  • 319
  • 3
  • 16
  • 3
    Does this answer your question? [How create a new deep copy (clone) of a List?](https://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt) and [Deep copy of List](https://stackoverflow.com/questions/4226747/deep-copy-of-listt) and [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) and [Is there any better deep clone methods for list?](https://stackoverflow.com/questions/44329919/is-there-any-better-deep-clone-methods-for-list) –  May 29 '21 at 07:43
  • 1
    First, you need to set your `temp` variable to `original.ToList()`. Right now, `temp` is still set to `original` because you’re not storing the result of `ToList()`. Importantly, `ToList()` doesn’t modify the _existing_ list, but rather returns a _new_ one. In addition, however, the objects _in_ the list are _also_ references, and since you’re operating on those, they also need to be cloned, as @OlivierRogier infers above. – Jeremy Caney May 29 '21 at 07:47
  • 1
    Thanks @OlivierRogier. I created an extension method for cloning https://stackoverflow.com/a/222640/5787668. Later i was able to to `original.ForEach(row => temp.Add(row.Clone().ToList()));` – Abhilash V May 29 '21 at 08:13

0 Answers0