I have a view model that contains a fill object and an rx object. Above the code shown below I have a List of fills and a List of rxs. These are being filled correctly.
Below, I set the fill and rx objects in an instance of my viewmodel to what is in the first element of each list. Then I add the instance of my viewmodel to a List of MyViewModels and restart the loop. However, right before restarting the loop, I remove the first element in the List of fills and the List of rxs so that on the next cycle my viewmodel objects will be different.
The problem is, when I debug, on each iteration of the loop, in the List of MyViewModels each viewmodel’s objects are being set equal to the new values from the fill list and rx list.
This has to be something so simple that Im overlooking. Thanks in advance.
for (int i = 0; i < f; i++)
{
_myViewModel.fill = FillList.ElementAt(0);
_myViewModel.rx = RxList.ElementAt(0);
MyList.Add(_myViewModel);
FillList.RemoveAt(0);
RxList.RemoveAt(0);
}
return View(MyList);
To me it seems like you’re creating the
_myViewModeloutside of the for loop, so the_myViewModelis one object.You’re not adding a clone or something of
_myViewModelto theMyListlist, but a reference to it. So next time the loop goes through and changes_myViewModelthe items already in the list change too.You need to create the a new myViewModel object inside the loop