user3646717 user3646717 - 1 year ago 45
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>();
foreach (int item in array)

It throws an 'System.InvalidCastException'. But I can't figure it out HOW to solve it.

Answer Source

You can use a lambda

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