I have a method that iterates through a list of objects and if it finds one that matches a certain criterion, it is supposed to delete it:
public static void MakeChanges(MappingFileModel modelWithChanges)
{
foreach (var mapping in Mapping)
{
if (mapping.ScanIndex.Equals(modelWithChanges.ScanIndex))
{
if (modelWithChanges.Column == -1)
{
Mapping.Remove(mapping);
}
}
}
}
Fairly simple, I would have thought: The method takes an instance of a MappingFileModel
called modelWithChanges
, then iterates over the list, finds the instance where the ScanIndex
strings match. It then checks if the Column == -1
, (I've deleted the else
statements for other options for brevity). So, if those two if
statements evaluate to true
, I want to remove mapping
from the list Mapping
.
Problem is, it doesn't remove it. I doesn't throw an error, either. It just doesn't do it. It does hit the statement if I set a breakpoint. I have also tried:
Mapping.RemoveAt(Mapping.IndexOf(mapping));
That does through an Index out of range error, which would indicate that my code can't locate mapping
in Mapping
. That makes no sense, since I am iterating over Mapping
?
Update:
Thanks to pointing out the other article... I edited my code to the following:
public static void MakeChanges(MappingFileModel modelWithChanges)
{
for (var i = 0; i<Mapping.Count; i++)
{
if (Mapping[i].ScanIndex.Equals(modelWithChanges.ScanIndex))
{
if (modelWithChanges.Column == -1)
{
Mapping.RemoveAt(i);
}
}
}
}
It still doesn't remove that object...
Update 2:
Ok, so I have now gone one step further and created a variable outside the loop... and it still doesn't delete the object. It's there. There is no error.
public static void MakeChanges(MappingFileModel modelWithChanges)
{
var deleteIndex = -1;
for (var i =0; i<Mapping.Count; i++)
{
if (Mapping[i].ScanIndex.Equals(modelWithChanges.ScanIndex))
{
if (modelWithChanges.Column == -1)
{
deleteIndex = i;
}
}
}
if (deleteIndex != -1)
{
Mapping.RemoveAt(deleteIndex);
}
}