Remove items from a List<T> while enumerating

Here is a simple way to remove items from currently enumerated list.
Put the list in while loop and make a manual index counter (var ind=0). Within while loop, every time items is removed decrease the index counter, otherwise increase the index.


private static void RemoveDirty(List<Element> lst)
{
var ind = 0;
while(ind<lst.Count)
{
var el= lst[ind];
if (el.IsDirty)
{
lst.RemoveAt(ind);
// in case items is removed decrease the index
ind--;
}
// increase the index when nothing is hepend
ind++;
}
}

Posted Dec 03 2014, 01:55 PM by Bahrudin
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.