0

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.

Cainnech
  • 439
  • 1
  • 5
  • 17
  • 3
    Why not just `Points = new List(x.Points)`? – Sami Kuhmonen Oct 09 '18 at 05:08
  • That simple huh... It's annoying when it turns out to be something that easy... :-) Thanks @SamiKuhmonen – Cainnech Oct 09 '18 at 05:23
  • Can I ask an additional question? How could I copy only a specific amount of entries? So in total, there are 7 entries in the list Points. If I would only like to copy the value of the first 4 into the new list and leave the other 3 values empty. How could I do that? – Cainnech Oct 09 '18 at 06:15
  • For you additional question, you can modify previous answer to `Points = new List(x.Points.Take(4))` – Kamil Folwarczny Oct 09 '18 at 06:54
  • Thank yo for your reply @KamilFolwarczny, but that only shows me the first 4 which is a good start, but I would like to have the 4 first values of the original list and to have the remaining items in the list to be 0. The size of the list should always stay the same. Is that possible? – Cainnech Oct 09 '18 at 06:58

1 Answers1

0

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.

Kamil Folwarczny
  • 581
  • 1
  • 3
  • 13