Steven Lam

Steven Lam

  • NA
  • 15
  • 1.5k

Foreach loop changes iterated variable but not main set

Apr 21 2022 7:45 PM

I am very confused as to why my foreach loop is not changing any of the code.

This is the code:

foreach (var device in job.JobDeviceTypes)
{
    var location = (await _IDeviceService.GetDevicesInStorageByDeviceType(device.DeviceType.DeviceTypeId, job.TeamId)).ToList().Select(x => x.Location.LocalId0).Distinct().ToList();
    device.Local_Id0 = location;
}

When running the code, the value of location and device.Local_Id0 are both changed. However, the actual set that is being iterated over (job.JobDeviceTypes) does not change. job is a public class whose member JobDeviceTypes is of type public IEnumerable<JobDeviceTypeDTO>. device (the value being iterated) is of type JobDeviceTypeDTO. I understand that I can not change device within this foreach loop, but shouldn't I be able to change its members? Or, does this have something to do with the fact that JobDeviceTypes is of type IEnumerable? If it is because of the fact it is IEnumerable, how would I go about changing it so job.JobDeviceTypes actually changes?

I have done some testing where I even ran: job.JobDeviceTypes.ToList()[0].Local_Id0.Add("0"); and the entry wasn't being added. 


Answers (1)