排序在C#中的列表框项目 [英] Sort the listbox items in C#
问题描述
我发展,我显示一个列表框中的项目是从数据库中获取的网页。动态我加了一些物品进去。它添加到列表框的末尾,所以我想后,我将项目添加到列表框项目进行排序。我试图的ArrayList
进行排序,但它不工作。
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.
推荐答案
我知道这个问题是很老了,但我一直在寻找这样做没有比较器类的方式的ArrayList等,所以我想我会贴方法我用了别人:
I know this question is quite old, but 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:
请注意,我的方法使用LINQ to对象,所以它只会在框架的新版本。
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>());
这篇关于排序在C#中的列表框项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!