The example Use a custom sort order for ListBox or ComboBox items in C# shows how to sort numeric values.
This example uses the same basic approach: make an array of values, sort them as you want them displayed, and then display them in the ComboBox or ListBox. The only real change is in sorting the items. The following code shows how this program uses LINQ to perform its magic. It assumes the items have the form “10 – Beginning Database Design Solutions” so a numeric value is followed by a space and then some text.
// Sort the values. var sort_query = from string value in values orderby int.Parse(value.Split(' ')) select value; // Display the result. string results = sort_query.ToArray(); cboBooks.DataSource = results; lstBooks.DataSource = results;
The query examines the items in the values array. It orders the items by the expression int.Parse(value.Split(' ')). That splits the value at the string’s spaces and then takes the first piece. That will be the numeric part at the beginning of the string. It parses that value into an integer so the query orders the values numerically not alphabetically.
The select clause simply selects the entire value.
The code finishes by calling the query’s ToArray method to copy the selected items (in sorted order) into an array. It saves the result in the ComboBox and ListBox controls’ DataSource properties. Because the two controls have the same DataSource value, they are linked together. See the post Link ComboBox and ListBox data sources in C# for more information on linked data sources.