如何将项目插入到按字母顺序排列的列表框中? [英] How can I insert an item to a listbox in its alphabetical place?

查看:57
本文介绍了如何将项目插入到按字母顺序排列的列表框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个网页,其中显示了一个列表框项目,这些项目是从数据库中获取的.动态地,我在其中添加了一些项目.它添加到列表框的末尾,因此我想在添加项目后对列表框项目进行排序.我尝试使用 Arraylist 进行排序,但是无法正常工作.

解决方案

我正在寻找一种在没有比较器类,ArrayLists等的情况下进行此操作的方法.>

请注意,我的方法使用LINQ to Objects,因此它仅适用于更新版本的Framework.

 //获取列表项的启用LINQ的列表List< ListItem>list =新的List< ListItem>(ListBoxToSort.Items.Cast< ListItem>());//根据需要使用LINQ to Objects订购物品list = list.OrderBy(li => li.Text).ToList< ListItem>();//从列表框中删除无序的项目,因此我们不会重复ListBoxToSort.Items.Clear();//现在添加回我们已排序的项目ListBoxToSort.Items.AddRange(list.ToArray< ListItem>()); 

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>());

这篇关于如何将项目插入到按字母顺序排列的列表框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆