views:

535

answers:

2

Hey, I have a problem with a foreach statement in my project.

So far I have the code:

    foreach(object i in listboxFiles.Items)
    {
        if (i == ".ftpquota")
        {
            listboxFiles.Items.Remove(i);
        }
        if (i == ".")
        {
            listboxFiles.Items.Remove(i);
        }
        if (i == "..")
        {
            listboxFiles.Items.Remove(i);
        }
    }

I have this in a 1 second timer,

it gets the item name all right but when it gets to the if statements but it says that they do not match, but they do?

Any ideas?

Thanks.

+4  A: 

First thing, you are changing a collection while iterating over it. This cannot work, so your code is fundamentally broken.

There are several ways to fix this; the simplest in your case would be to copy the items collection, iterating over the copy and changing (= removing from) the original:

var items = new System.Collections.ArrayList(listboxFiles.Items);

foreach (var item in items) {
    if (item.Equals("."))
        listboxFiles.Items.remove(item);
    …
}

Secondly, you are comparing an object to a string, hence the == operator does reference equality checking rather than testing for string equality. Either use Equals or do an appropriate cast.

Konrad Rudolph
Hey, I tried this but I am not getting the error of that I cannot convert an object to a bool. Also im getting 'Cannot assign to 'i' because it is a 'foreach iteration variable'
Crazyd22
@Crazy: try again, using *my* code. You obviously did something differently because my code does *not* give these errors: I do not assign to the loop variable, and I do not convert to a boolean.
Konrad Rudolph
Will try this thanks
Crazyd22
I tried this but I am getting back these errors: http://img38.yfrog.com/img38/6858/captureybe.jpg
Crazyd22
Right, my bad. Try again using the updated code: it uses `ArrayList` instead of the generic `List<T>`.
Konrad Rudolph
Perfect, works thanks! :)
Crazyd22
+1  A: 

The equality check is not working because you should cast to string first and do an appropriate string comparison.

e.g.

if (string.Equals((string)i, ".ftpquota", StringComparison.Ordinal))

If you remove items from a collection of items whilst iterating through the collection, you may well run into trouble. One way to get around this problem is to start with the last item and count backwards, thus any removals you do will not affect the remaining items of the collection, e.g.

for(var i = listboxFiles.Items.Count - 1; i >= 0; --i)
{
    var item = listboxFiles[i];
    if (...)
    {
        listboxFiles.Items.RemoveAt(i);
    }
}
AdamRalph