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.
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:
Options to consider:
DeepClone()
method to GenList
, to keep the logic in one place however many places need it.GenList(GenList)
which copies appropriatelyGenList
immutable) at which point shallow clones of collections are sufficient.See more on this question at Stackoverflow