I have 2 lists, allCharges and selectedCharges, where each item in selectedCharges is contained in allCharges.
I want to create a third list (called charges) that is a copy of all charges, but with a boolean property of "Selected" for each item set to true if the charge is in the list of selected charges.
This is fine if I am only doing this once; however, I am trying to perform the same operation five times, rewriting "charges" each time while saving "charges" to my "typeSettingsList".
IList<TypeSettings> typeSettingsList = new List<TypeSettings>();
var typeId = 1;
while (typeId < 6)
{
var links = _linkChargeTypeRepo.Query().Where(l => l.TypeId == typeId);
var allCharges = _chargeRepo.GetAll().ToList();
var selectedCharges = links.Select(l => l.ChargeType).ToList();
selectedCharges.ForEach(c => c.Selected = true);
var nonSelectedCharges = allCharges.Except(selectedCharges).ToList();
nonSelectedCharges.ForEach(c => c.Selected = false);
var charges = nonSelectedCharges.Concat(selectedCharges).ToList();
var settingsWithType = new TypeSettings
{
Type = _typeRepo.Get(typeId),
Charges = charges
};
typeSettingsList.Add(settingsWithType);
typeId++;
}
return settingsWithType;
My problem is that each "Charges" object in my typeSettingsList ends up getting overwritten with the charges object that is created on the last iteration, even though the variable is declared inside the while loop (and should therefore be a new object reference with each iteration).
Is this just an incorrect understanding of how variables inside while loops should work?
How can I make it so my "charges" list isn't overwritten with each iteration?