Display items in a ListBox sorted in numeric order in C#

If you set a ListBox's Sorted property to true, the control sorts its contents. Unfortunately it can only sort its contents in alphabetic order. If the items are numeric, that may not be what you want.

The following code shows how you can display the items sorted in numeric order.

// Display items sorted in numeric order.
private void Form1_Load(object sender, EventArgs e)
{
// Get the items and convert them into an array of string.
string[] items = lstNumeric.Items.Cast().ToArray();

// Use LINQ to convert into an array of int.
var to_int =
from value in items
select int.Parse(value);
int[] keys = to_int.ToArray();

// Sort the items array using the keys to determine order.
Array.Sort(keys, items);

// Display the results.
lstNumeric.Sorted = false;
lstNumeric.DataSource = items;
}

The code first gets the items as an array of strings. It then uses LINQ to select the numeric values of the items. The LINQ query could also do other things to modify the data. For example, if the values each begin with a letter as in A100, it could select int.Parse(value.Substring(1)) to remove the letter from the numeric value.

The program executes the query and saves the resulting numeric values in an array.

The program then uses the Array.Sort method to sort the original items. It uses the array of numeric values as keys to use in sorting. The result is that they values array contains the original values sorted by the numeric values.

The code finishes by displaying the original values sorted.

The same technique will work with the ComboBox control.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.