I want to make a copy of a list of records. The code below only copies references of the records so changing Data in myRecs1 also changes it in MyRecs2. Besides doing a loop in a loop, is there an easy way to get a full copy of myRecs2 from myRecs1?
static void Main(string[] args)
{
List<MyRec> myRecs1 = new List<MyRec>()
{
new MyRec() {Id = 1, Data = "001"},
new MyRec() {Id = 2, Data = "002"},
new MyRec() {Id = 3, Data = "003"}
};
//List<MyRec> myRecs2 = myRecs1.ToList(); // does not work of course
// ugly but works
List<MyRec> myRecs2 = myRecs1.Select(rec => new MyRec()
{
Id = rec.Id,
Data = rec.Data
}).ToList();
myRecs1[2].Data = "xxx";
foreach (var rec in myRecs2)
{
Console.WriteLine(rec.Data);
}
}
public class MyRec
{
public int Id { get; set; }
public string Data { get; set; }
}
- edited to show working example I don't like