BLOG.CSHARPHELPER.COM: Sort partly numeric items in a ComboBox or ListBox in C#
Sort partly numeric items in a ComboBox or ListBox in C#
The example Sort items in a ComboBox or ListBox numerically in C# shows how to sort numeric values, but often the values you need to display begin with a number and then continue with text. In that case, the earlier example won't work because it needs to treat the values as numbers. This example handles this situation.
The basic approach is the same as before: 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 the 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 value in values orderby int.Parse(value.Split(' ')[0]) select value;
// Display the result. cboBooks.DataSource = sort_query.ToArray(); lstBooks.DataSource = sort_query.ToArray();
The query examines the items in the values array. It orders the items by the expression int.Parse(value.Split(' ')[0]). 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 the order into an array. It saves the result in the ComboBox's and ListBox's DataSource properties. (It calls ToArray twice so each control gets its own copy of the values so they are not linked together.)
Comments