views:

458

answers:

1

So far I've found 2 ways to delete selected items from a listbox (winform):

1.

ListBox.SelectedObjectCollection tempCollection = new ListBox.SelectedObjectCollection(myListBox);
for (int i = tempCollection.Count - 1; i >= 0; i--)
{
    myListBox.Items.Remove(tempCollection[i]);
}

2.

while (myListBox.SelectedItems.Count > 0)
{
    myListBox.Items.Remove(myListBox.SelectedItem);
    // or
    //myListBox.Items.Remove(myListBox.SelectedItems[0]);
}

The 2nd way is easy to understand, but the 1st one is strange for me. They're both work for me, I just want to know the difference?

A: 

The first way is written really strangely. It looks strange because it goes backwards. This is so that it doesn't upset the collection of selected items. The selected items collection isn't fully created, it's an Enumerable collection, and items come off it only when you ask for them. You can't use a foreach, because the collection of selected items keeps changing as you remove items.

I actually prefer the second way. Besides, whatever reads easier is easier to maintain. The first one reads: get the selected items, go through them backwards, removing each from the list.

The second one reads: while there are selected items, remove the first available selected item.

Much better the second way.

Ilya Tchivilev