Reputation: 43
I have this code:
foreach (KeyValuePair<string, KeyValuePair<float, float>> sysCoordTop in allSysCoords)
{
List<string> tempNameList = new List<string>();
float xTop = sysCoordTop.Value.Key;
float yTop = sysCoordTop.Value.Value;
string nameTop = sysCoordTop.Key;
foreach (KeyValuePair<string, KeyValuePair<float, float>> sysCoordBottom in allSysCoords) {
float xBottom = sysCoordBottom.Value.Key;
float yBottom = sysCoordBottom.Value.Value;
float xDiff = System.Math.Abs(xTop - xBottom);
float yDiff = System.Math.Abs(yTop - yBottom);
string nameBottom = sysCoordBottom.Key;
if (xDiff < 5f && yDiff < 5f && nameBottom != nameTop) {
tempNameList.Add(nameBottom);
Debug.Log($"{nameBottom} added to temp list at {nameTop}");
}
}
sysDict.Add(nameTop, tempNameList);
Debug.Log("temp list written to dict");
tempNameList.Clear();
}
My problem is that the lines below do not execute when I expected them to, but rather they execute once before the nested loop, even though I assumed them to execute once every iteration of the first foreach loop.
sysDict.Add(nameTop, tempNameList);
Debug.Log("temp list written to dict");
tempNameList.Clear();
Now, I'm well aware that this way of nesting loops is not the best way to do things. I'm not asking this is to get unhelpful comments about how bad it is to write with nested loops. I'm asking this to get an answer to the question I asked. If you do however decide to inform me of how bad it is to write nested loops, please also enlighten me on how I should do it instead.
Upvotes: 1
Views: 124
Reputation: 11364
Don't use Clear method on tempItem, instead re-initialize that object at start of each iteration.
Clearing it will clear the item in list as well.
When you add the object to dictionary, you add reference and not the values. When you clear the object, you clear values and everything referencing that object will have the same effect (no values). Instead of clearing, re-initialize the object
Upvotes: 4