title: C# List<t>.ForEach(delegate(type t) and how to remove items as the list is iterated through
body: <p>This may be considered bad programming, but prior to .net 4, I used to heavily use code similar to this:</p>
  
  <pre><code>    enemyList.ForEach(delegate(Enemy e)
      {
          e.Update();
          if (someCondition)
                enemyList.Remove(e);
      });
  </code></pre>
  
  <p>Now, I'm going through an updating some old projects, and there are a <em>LOT</em> of code thats going to have to be changed since ForEach was removed.. Now, I do have an extension to allow me to use the ForEach :</p>
  
  <pre><code>    public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; sequence, Action&lt;T&gt; action)
      {
          if (sequence == null) throw new ArgumentNullException("sequence");
          if (action == null) throw new ArgumentNullException("action");
          foreach (T item in sequence)
              action(item);
      }
  </code></pre>
  
  <p>I know I can do this:</p>
  
  <pre><code>    var index = 0;
      while(index &lt; enemyList.Count)
      {
          if(condition)
              enemyList.RemoveAt(index);
          else
              index++;
      }
  </code></pre>
  
  <p>But some of those would be a pain to rewrite like that.. Is there any way to add that functionality back so that I can iterate through that list, remove the items I need without having to go back and rewrite and edit all of those functions ? I still consider myself a newbie to coding, and I just can't figure this one out.. Any help would be appreciated!</p>
  
  <p><em><strong></em>**<em>*</em>**<em>*</em>***<em></strong> EDIT <strong></em>**<em>*</em>**<em>*</em>**<em>*</em></strong></p>
  
  <p>So I guess it boils down to rewriting a lot of code.. I have a lot of code such as this that I just pulled out of a project:</p>
  
  <pre><code>            GameplayScreen.gameWorld.shipList.ForEach(delegate(Ship s)
              {
                  if (eS.originalShipsID == s.shipID)
                  {
                      if (!eS.Alive || eS.health &lt;= 0)
                      {
                          // this one sunk...
                          string log = "0" + s.shipName + " was sunk in battle.. All crew and cargo were lost.";
                          AddLogEntry(log);
                          totalCrewLost += s.currentCrew;
                          GameplayScreen.gameWorld.shipList.Remove(s);
                      }
                  }
              });
  </code></pre>
  
  <p>I was just hoping there was a way to not have to rewrite all of that.. So time to update and change the way I code apparently. Thanks!</p>