简体   繁体   中英

What is the most efficient way to delete all selected items in a ListViewItem collection?

My user is able to select multiple items in a ListView collection that is configured to show details (that is, a list of rows).

What I want to do is add a Delete button that will delete all of the selected items from the ListViewItem collection associated with the ListView .

The collection of selected items is available in ListView.SelectedItems , but ListView.Items doesn't appear to have a single method that lets me delete the entire range. I have to iterate through the range and delete them one by one, which will potentially modify a collection I'm iterating over.

So, what I'm basically after is the opposite of AddRange() .

If you have a collecion of your selectedItems, you can simply call remove on each of them instead of iterating over the ListView.

There is a method on ListViewItem called Remove() .

ListView listview = <reference to ListView>;
foreach (ListViewItem item in listView.SelectedItems)
{
  item.Remove();
}

This removes the iteration through all the items and only removes your selected items.

As far as I know, there is no way other than to delete them individually.

Wrap your deletion algorithm in ListView.BeginUpdate() and ListView.EndUpdate() calls. This way you won't get the slowdown of repainting on each delete.

Additionally, if you delete them in reverse order, I believe the underlying structure will have less to do.

Also, if the number of items you are deleting is a significant percentage of the total number of items, you might get more performance by clearing the list and AddRange() ing them back again.

对我来说,在linq 2 sql中我使用:

mylist.Clear();

Perhaps you could try something along the lines of the following:

var ItemsToDelete = ... // wherever you get the collection of items to delete from
var RemainingItems = yourList.FindAll(delegate(ListItem x) {
  return !ItemsToDelete.Contains(x)
});
yourListView.DataSource = RemainingItems;
yourListView.DataBind();

or just assign the remaining items to the existing control, or whatever you prefer.

(edited formatting slightly)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM