简体   繁体   English

如何在C#中对listBox进行排序?

[英]How to sort a listBox in C#?

I have typed numbers in a textbox and added them into a listBox. 我已经在文本框中键入数字,并将其添加到列表框。 Now I need to order that listbox. 现在,我需要订购该列表框。 This is my try: 这是我的尝试:

int[] array = listBox1.Items.Cast<int>().ToArray<int>();
Array.Sort(array);
listBox1.Items.Clear();
foreach (int item in array)
{
    listBox1.Items.Add(item);
}

It throws an 'System.InvalidCastException'. 它将引发“ System.InvalidCastException”。 But I can't figure it out HOW to solve it. 但我不知道如何解决。

This is as simple as 这很简单

listBox1.Sorted = true;

UPDATE 更新

var array = new object[listBox1.Items.Count];
listBox1.Items.CopyTo(array, 0);
listBox1.Items.Clear();
var sortedArray = array.Select(n => (object)Convert.ToInt32(n)).OrderBy(n => n).ToArray();
listBox1.Items.AddRange(sortedArray);

You can use a lambda 您可以使用lambda

var array = listBox1.Items.OfType<string>().Select(x => int.Parse(x))
                             .ToArray();

First, I want to say that it is not a good idea to store data inside a control. 首先,我想说在控件内部存储数据不是一个好主意。 Always put your data inside types that can handle them like a List, Dictionary, etc. and then bind that to your listbox object. 始终将数据放入可以处理它们的类型(如列表,字典等)中,然后将其绑定到列表框对象。 I guess you are working on windows forms. 我猜您正在使用Windows窗体。 Then add a property to your form and put all your data in it. 然后将一个属性添加到您的窗体并将所有数据放入其中。

something like this 像这样的东西

public partial class Form1 : Form
{
List<string> _items = new List<string>(); // <-- Add this

public Form1()
{
    InitializeComponent();

    _items.Add("One"); // <-- Add these
    _items.Add("Two");
    _items.Add("Three");

    listBox1.DataSource = _items;
}
public void add()
{
 _items.Add("four");
 _items.Sort();
}
}

ListBox items can cast to string. ListBox项可以转换为字符串。 So, You must cast it to string[], then convert to int[], then sort it and finally add sorted data to ListBox. 因此,您必须将其转换为string [],然后转换为int [],然后对其进行排序,最后将排序后的数据添加到ListBox。

        string[] strArray = listBox1.Items.Cast<string>().ToArray();
        int[] intArray = strArray.Select(x => int.Parse(x)).ToArray();
        Array.Sort(intArray);
        listBox1.Items.Clear();
        foreach (int item in intArray)
        {
            listBox1.Items.Add(item);
        }

I hope this will be useful. 我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM