I develop a webpage in that I display a list box items which is fetched from a database. Dynamically I added some items into it. It adds to the end of the list box, so I want to sort the list box item after I add items. I tried Arraylist
for sorting, but it is not working.
I was looking at a way of doing this without comparer classes, ArrayLists etc. So I thought I'd paste the method I had used for others:
Please note that my method uses LINQ to Objects, so it will only work in newer versions of the Framework.
// get a LINQ-enabled list of the list items
List<ListItem> list = new List<ListItem>(ListBoxToSort.Items.Cast<ListItem>());
// use LINQ to Objects to order the items as required
list = list.OrderBy(li => li.Text).ToList<ListItem>();
// remove the unordered items from the listbox, so we don't get duplicates
ListBoxToSort.Items.Clear();
// now add back our sorted items
ListBoxToSort.Items.AddRange(list.ToArray<ListItem>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With