Sorting a list of items in a list box

2019-01-14 18:28发布

I want to get an bunch of items from a list box, add them to an array, sort it, then put it back into a different listbox. Here is what I have came up with:

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

But it doesnt work. Any ideas?

10条回答
Anthone
2楼-- · 2019-01-14 19:18

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!

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-14 19:22

Add the items to array and close the loop. Then sort the array values and bind it to listbox

查看更多
戒情不戒烟
4楼-- · 2019-01-14 19:25

also you can use "extension methods" that i wrote:

public static class ExtensionMethods
{
    public static void Sort(this ListControl lb, bool desc = false)
    {
        var list = lb.Items.Cast<ListItem>().ToArray();
        list = desc
                    ? list.OrderByDescending(x => x.Text).ToArray()
                    : list.OrderBy(x => x.Text).ToArray();
        lb.Items.Clear();
        lb.Items.AddRange(list);
    }
    public static void SortByValue(this ListControl lb, bool desc = false)
    {
        var list = lb.Items.Cast<ListItem>().ToArray();
        list = desc
                    ? list.OrderByDescending(x => x.Value).ToArray()
                    : list.OrderBy(x => x.Value).ToArray();
        lb.Items.Clear();
        lb.Items.AddRange(list);
    }
    public static void SortByText(this ListControl lb, bool desc = false)
    {
        lb.Sort(desc);
    }
    public static void SortRandom(this ListControl lb)
    {
        var list = lb.Items.Cast<ListItem>()
                            .OrderBy(x => Guid.NewGuid().ToString())
                            .ToArray();
        lb.Items.Clear();
        lb.Items.AddRange(list);
    }
}
查看更多
Animai°情兽
5楼-- · 2019-01-14 19:29
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); 
}
查看更多
登录 后发表回答