To quickly select all the items in a ListView
, have look at the long answer to this question. The method outlined there is virtually instantaneous, even for lists of 100,000 objects AND it works on virtual lists.
ObjectListView provides many helpful shortcuts like that.
However, there is no way to automatically invert the selection. SLaks method will work for normal ListViews, but not for virtual lists since you can't enumerate the Items
collection on virtual lists.
On a virtual list, the best you can do is something like you first suggested::
static public InvertSelection(ListView lv) {
// Build a hashset of the currently selected indicies
int[] selectedArray = new int[lv.SelectedIndices.Count];
lv.SelectedIndices.CopyTo(selectedArray, 0);
HashSet<int> selected = new HashSet<int>();
selected.AddRange(selectedArray);
// Reselect everything that wasn't selected before
lv.SelectedIndices.Clear();
for (int i=0; i<lv.VirtualListSize; i++) {
if (!selected.Contains(i))
lv.SelectedIndices.Add(i);
}
}
HashSet
is .Net 3.5. If you don't have that, use a Dictionary
to give fast lookups.
Be aware, this will still not be lightning fast for large virtual lists. Every lv.SelectedIndices.Add(i)
call will still trigger a RetrieveItem
event.