user3646717 user3646717 - 3 months ago 10
C# Question

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'. But I can't figure it out HOW to solve it.

Answer

You can use a lambda

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