Sorting a list of items in a list box

Try this:

var list = lstBox.Items.Cast<ListItem>().OrderBy(item => item.Text).ToList();
lstBox.Items.Clear();
foreach (ListItem listItem in list)
{
    lstBox.Items.Add(listItem);
}

If you need it to sort by the Values, just switch out item.Text with item.Value.

Enjoy!


You could just use the ListBox.Sorted built in functionality

  foreach (object o in listBox4.Items)
  {
    listBox5.Items.Add(o);
  }
  listBox5.Sorted = true;

Setting ListBox5.Sorted=true will ensure that the items in the listbox are sorted and any subsequent items added to the listbox will be added in the correct order.

Of course this assumes that you have simple sort requirements as suggested by your example.


ArrayList q = new ArrayList(); 
foreach (object o in listBox4.Items) 
        q.Add(o);
} 
q.Sort(); 
listBox5.Items.Clear();
foreach(object o in q){
    listBox5.Items.Add(o); 
}