I'm working on a project where I have a list of objects with a nested list of which I want to make a backup before I update the original list.
I'm close but I'm having trouble finding the correct syntax so I hope you can help me out here.
This is the original class:
public class TeamClass
{
public string Country { get; set; }
public string CountryCode { get; set; }
public List<double> Points { get; set; }
}
List<TeamClass> originalList = new List<TeamClass>();
Just before I update the points on the OriginalList I want to create a deep copy of the OriginalList so I can "undo" the changes.
Currently I'm using the code below:
var backupList = Simulation.ConvertAll(x => new TeamClass
{
Country = x.Country,
CountryCode = x.CountryCode,
Points = new List<double>(x.Points.ConvertAll(p => new double()))
})
.OrderByDescending(o => o.Points.Sum())
.ToList();
Although this code creates a deepcopy of the original list, it replaces all of the points in the list Points by 0 (because of the new double())
However using
Points = x.Points
gives me the correct points but they get updated when the original list gets updated.
I think I have to do something like
Points = new List<double>().AddRange(x.Points)
But I can't find the correct syntax.
Any help is appreciated.
To answer you additional question from comments. It can be done with something like this.
int N = 4; // Number of desired elements with value
var backupList = Simulation.ConvertAll(x => new TeamClass
{
Country = x.Country,
CountryCode = x.CountryCode,
Points = new List<double>(x.Points.Take(N).Concat(x.Points.Skip(N).ToList().ConvertAll(p => new double())));
})
.OrderByDescending(o => o.Points.Sum())
.ToList();
Since double is not nullable datatype, all values after N will be converted to 0.