RSS

Remove items from a collection that matches a constraint

06 May

If you want to remove some elements that are matching a constraint from a list, and you use a foreach loop to traverse the list you get the exception you will get an exception saying that you cannot change the collection during an enumeration of if you remove an item.

List list = new List() { 6, 8, 7, 8, 9,6, 3, 7,8, 4, 10, 0 };
foreach (var item in list)
{
    if (item > 5)
    {
        list.Remove(item);   //here you will get the exception
    }
}

This is because you cannot modify a collection during enumerating it. Despite you cannot remove an item, you also could not add any item. This problem could be addressed by changing the foreach-loop with a for-loop

List list = new List(){ 6, 8, 7, 8, 9,6, 3, 7,8, 4, 10, 0 };
for (int index = 0; index < list.Count; index++)
{
    var item = list[index];
    if (item > 5)
    {
        list.Remove(item);
    }
}

And the problem is solved! Or is it?

No it is not. Just watch the resulting list8,8,6,3,8,4,0 where it should be 3,4,0.

This is because you have following:

Position List content remove it
0 6,8,7,8,9,6,3,7,8,4,10,0 yes
1 8,7,8,9,6,3,7,8,4,10,0 yes
2 8,8,9,6,3,7,8,4,10,0 yes
3 8,8,6,3,6,3,7,8,4,10,0 no
4 8,8,6,3,7,8,4,10,0 yes
5 8,8,6,3,8,8,4,10,0 yes
6 8,8,6,3,4,10,0 yes
7 8,8,6,3,4,0

As you se, you skip some items. This problem can be addressed by not increasing indesif you find an item to remove or you traverse the list beginning at the end:

for (int index = list.Count -1; index >= 0; index--)
{
    var item = list[index];
    if (item > 5)
    {
        list.Remove(item);
    }
} 

Another possibility is to use the LINQ-Extension-Method RemoveAll

 list.RemoveAll(item=>item > 5); 
Advertisements
 
Leave a comment

Posted by on May 6, 2012 in C-Sharp, LINQ

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: