views:

73

answers:

3

I have a ListView and sorting is enabled, once I insert an item, how do I get that item's index?

I can use the ListViewItem returned by the Add method of ListView, but is its index before sort or after? And is it updated if it is sorted again? Like if I store the ListViewItem and the ListView is then sorted, will the ListViewItem I stored earlier, its Index property would be updated too?

A: 

Assuming you are adding a ListViewItem:

listView.Items.Add(myItem);
int index = listView.Items.IndexOf(myItem);
Kieren Johnstone
Is it fast? What is its complexity? Is it instant?
ListViewItem
Of course it's not instant. It's a computer, not magic.
Will Dean
@ListViewItem: It's not - O(n). Check my answer for a fast method.
Jaroslav Jandek
Why do you care about speed? The item lookup will not be a problem. If you have enough items to have to care about speed you'll have to use virtual mode anyway. Don't do any premature optimizations.
jgauffin
A: 

Try using listView.Items.IndexOfKey(name_of_your_item_goes_here) or listView.Items.IndexOf(your_new_item) if you care to create ListViewItems before adding them to list.

26071986
+1  A: 

Depends on how you add:

ListViewItem item = ...;
listView.Items.Add(item);
int index = item.Index;

or

ListViewItem item = listView.Items.Add("ItemName");
int index = item.Index;

To answer your questions that I missed before: yes, the indexes should be updated.

Jaroslav Jandek
Can I get O(1)? What is ListViewItem.Name property? Can I use it as a key like in a dictionary?
ListViewItem
@ListViewItem: It is an `O(1)` operation when using `listView.Items[5]`. You can use the `ListViewItem.Name` property as a key, but `listView.Items["name"]` is an `O(n)` operation and an `O(1)` operation **only when** the `<last accessed item>.Name == "name"`.
Jaroslav Jandek