I have an object called particle that has its own properties (position, velocity, etc.) and in my windows form I create a list of particles. This list of particles is then updated in the code (i.e. each particle’s position, velocity, etc. is updated in each iteration step).
What I want to do is add this List<Particle> to another list List<List<Particle>> each iteration (after clicking a button) so that I now have seperate lists of particles that I can compare.
This is what my code looks like (UpdateEngine is a class that creates a list of particles in its initialise method and then has other methods that update the values of the particles in its list):
public partial class frmMain : Form
{
private List<List<Particle>> listPlist;
private UpdateEngine Engine;
...
public frmMain()
{
InitializeComponent();
listPlist = new List<List<Particle>>();
Engine = new UpdateEngine();
}
...
//pressing this button iterates through a specified number of iterations
private void btPrep_Click(object sender, EventArgs e)
{
//create the particles and add the first list to the list of lists
Engine.Initialize();
listPlist.Add(Engine.ParticleList);
//iterate through the list of particles in Engine and update their properties
for(i = 0; i <= iterations; i++)
{
Engine.Update();
listPlist.Add(Engine.ParticleList);
}
}
}
What I see happening is that the first list is added before the iterations fine. The first list added in the for loop is added fine. Every list added thereafter changes all the lists in listPlist to be identicle to the current list.
An example of what I see when I run the code:
After initialization:
- listPlist(0) > Particle(0) > Position = 0,0
After first iteration:
- listPlist(0) > Particle(0) > Position = 0,0
- listPlist(1) > Particle(0) > Position = 1,1
After next iteration:
- listPlist(0) > Particle(0) > Position = 2,2
- listPlist(1) > Particle(0) > Position = 2,2
- listPlist(2) > Particle(0) > Position = 2,2
I’m not really sure how to fix this. Does anyone know why this is happening?
From what I understand from your question, the problem is that you are trying to make copies of a reference item, which is why you see all the list items changing.
You will need to make a deep clone of these list/particles so that they arent referencialy dependent.
You might have to add a new Copy Method or Constructor to the particle object to achieve this.
Something like
You can then create a copy of the original list something like