title: Unable to remove object from list in C#
body: <p>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:</p>
  
  <pre><code>public static void MakeChanges(MappingFileModel modelWithChanges)
  {
      foreach (var mapping in Mapping)
      {
          if (mapping.ScanIndex.Equals(modelWithChanges.ScanIndex))
          {
              if (modelWithChanges.Column == -1)
              {
                  Mapping.Remove(mapping);
              }
          }
      }
  }
  </code></pre>
  
  <p>Fairly simple, I would have thought: The method takes an instance of a <code>MappingFileModel</code> called <code>modelWithChanges</code>, then iterates over the list, finds the instance where the <code>ScanIndex</code> strings match. It then checks if the <code>Column == -1</code>, (I've deleted the <code>else</code> statements for other options for brevity). So, if those two <code>if</code> statements evaluate to <code>true</code>, I want to remove <code>mapping</code> from the list <code>Mapping</code>.</p>
  
  <p>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:</p>
  
  <pre><code>Mapping.RemoveAt(Mapping.IndexOf(mapping));
  </code></pre>
  
  <p>That does through an Index out of range error, which would indicate that my code can't locate <code>mapping</code> in <code>Mapping</code>. That makes no sense, since I am iterating over <code>Mapping</code>?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Thanks to pointing out the other article... I edited my code to the following:</p>
  
  <pre><code>public static void MakeChanges(MappingFileModel modelWithChanges)
      {
          for (var i = 0; i&lt;Mapping.Count; i++)
          {
              if (Mapping[i].ScanIndex.Equals(modelWithChanges.ScanIndex))
              {
                  if (modelWithChanges.Column == -1)
                  {
                      Mapping.RemoveAt(i);
                  }
              }
          }
      }
  </code></pre>
  
  <p>It still doesn't remove that object... </p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>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.</p>
  
  <pre><code>public static void MakeChanges(MappingFileModel modelWithChanges)
      {
          var deleteIndex = -1;
  
          for (var i =0; i&lt;Mapping.Count; i++)
          {
              if (Mapping[i].ScanIndex.Equals(modelWithChanges.ScanIndex))
              {
                  if (modelWithChanges.Column == -1)
                  {
                      deleteIndex = i;
                  }
              }
          }
  
          if (deleteIndex != -1)
          {
              Mapping.RemoveAt(deleteIndex);
          }
      }
  </code></pre>