tags:

views:

334

answers:

3

Hi,

I was debugging a co-workers program and ran across this issue in WPF.

It looks like the listBoxName.SelectedItems returns a list of selected items, in the order a user selects the item from the interface. This is a problem because I need to preserve the actual order the items.

Example:

the listbox is in Extended selectmode and my listbox contains something: runfirst, runsecond, runthird

the user is given an option to select what they want to run based from the listbox. They select runthird then runfirst. This causes runthird to appear at the top of the list and then runfirst. I guess i could sort the list before running a foreach but i was wondering if there is an easier way.

Thanks

+1  A: 

I think you gave the answer in your question.

Most of the time the order of selected items won't matter. Since it does for you, sorting the selected items before processing them seems to be the simplest solution. I can't really think of a simpler one, especially when the sorting should only add 1 line.

You can use the same Comparison<T> or IComparer<T> that was used to sort the original list. If you're binding to SelectedItems, you can use an IValueConverter to do the sorting.

Joel B Fant
I took your advice about sorting
Locke12
+3  A: 

What I did was use LINQ to return the selected items in index order. It is in VB.Net syntax, but it should be easy to fix up for C#.

Dim selecteditems = From selecteditem As ListBoxItem In ListBox1.SelectedItems _
                    Select selecteditem _
                    Order By ListBox1.Items.IndexOf(selecteditem)
Wade73
Using link probably would have worked as well
Locke12
A: 

Yeah I ended up iterating over all the items in the in the listbox and then checked if it was in selecteditems using contains as below

            foreach (<yourobject> item in listForSelection.Items)
            {
                if (listForSelection.SelectedItems.Contains(item))
                {
                     \\code here
                }
            }

Thanks for the help guys

Locke12