本文介绍了在C#中以数字方式对ListBox进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按数字对充满数字的列表框进行排序.为什么这行不通?

Im trying to sort a listbox full of numbers numerically. Why doesnt this work?

        {
            ArrayList Sorting = new ArrayList();
            Sorting.Add (lbNumbers.Text);
            int[] items = new int[Sorting.Count];
            Sorting.CopyTo(items);
            Array.Sort(items);
            lbNumbers.Items.Add(items);

        }

推荐答案

ArrayList Sorting = new ArrayList();

foreach (var o in listBox1.Items) {
    Sorting.Add(o);
}

Sorting.Sort();

listBox1.Items.Clear();

foreach (var o in Sorting) {
    listBox1.Items.Add(o);
}

已添加:对于降序排序,

1.创建一个ReverseSort类,如下所示:

1.Create a class ReverseSort as shown below:

// implementation:
public class ReverseSort : IComparer
{
    public int Compare(object x, object y)
    {
        // reverse the arguments
        return Comparer.Default.Compare(y, x);
    }
}

2.用以下行替换Sort的代码行:

2.Replace the code line of Sort with this line:

Sorting.Sort(new ReverseSort());

这篇关于在C#中以数字方式对ListBox进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:18