copy list into other list

I know this is asked many times and i am trying to implement same . I have list below

internal class GenList
{

    public string Col1 { set; get; }
    public string Col2 { set; get; }

}

List<GenList> MainList = new List<GenList>();

I want to copy list into other list and dont want content to change in cloned list if something is changed in main list. So i am trying to do below

List<GenList> cloned = MainList.ConvertAll(GenList => new GenList {});

I dont know what to enter inside those curly braces in above line.

Jon Skeet
people
quotationmark

dont want content to change in cloned list if something is changed in main list.

That sounds like you want a deep clone, basically. In other words, creating a new list where each element is a copy of an element in the original list, not just a reference to the same object as the original list refers to.

In your case, that's as simple as:

var cloned = MainList.ConvertAll(x => new GenList { Col1 = x.Col1, Col2 = x.Col2 });

Or with LINQ:

var cloned = MainList.Select(x => new GenList { Col1 = x.Col1, Col2 = x.Col2 })
                     .ToList();

But note that:

  • If you add a new property, you will need to change this code
  • If you add a property of a mutable type, you'd need to clone that too

Options to consider:

  • Adding a DeepClone() method to GenList, to keep the logic in one place however many places need it.
  • Adding a constructor instead: GenList(GenList) which copies appropriately
  • Using immutable types instead (e.g. make GenList immutable) at which point shallow clones of collections are sufficient.

people

See more on this question at Stackoverflow