Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach statement in listbox

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?

like image 501
Crazyd22 Avatar asked Feb 14 '10 11:02

Crazyd22


2 Answers

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.

like image 108
Konrad Rudolph Avatar answered Oct 06 '22 22:10

Konrad Rudolph


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);
    }
}
like image 27
Adam Ralph Avatar answered Oct 06 '22 20:10

Adam Ralph