Reputation: 268
I'm having trouble understanding why this loop is modifying the the object in the collection that I am looping through rather than just the tempProvider
object inside of the loop.
This code is in another loop that goes through a list of counties. This provider has 7 offices to begin with and then when I hit the tempProvider.Offices =
... line the first time through it only has one matching office in the county so it wipes the rest of the offices for the Provider object in countyPcps, which affects other code where I have to loop through the offices.
Can anyone tell me what is going on and how I might correct this?
I've tried a few things, including removing the OrderBy(x=> x.LastName
, making this a for loop, and removing the .ToList()
for the countyPcps variable. I don't get what is happening and it seems like it should be really straight forward...
var countyPcps =
providersForCounty.Where(x =>
x.SpecialtiesAndCerts != null && x.SpecialtiesAndCerts.Any() &&
x.SpecialtiesAndCerts.Contains(specialty)).ToList();
foreach (Provider provider in countyPcps.Where(x => x.LastName != null).OrderBy(x => x.LastName))
{
Provider tempProvider = provider;
tempProvider.Offices = tempProvider.Offices.Where(x => x.County == county).ToList();
xmlSerializer.Serialize(xmlWriter, tempProvider, ns);
}
Upvotes: 1
Views: 73
Reputation: 292425
I'm having trouble understanding why this loop is modifying the the object in the collection that I am looping through rather than just the tempProvider object inside of the loop.
Because it's the same object. When you assign provider
to tempProvider
, you just copy the reference to the object, not the object itself; provider
and tempProvider
still refer to the same instance of the Provider
class. If Provider
was a value type, you would get a copy of the object, but since it's a reference type, you just get a copy of the reference.
Upvotes: 3