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 it says that they do not match, but they do?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With