Sort partly numeric items in a ComboBox or ListBox in C#

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(' ')[0])
    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(' ')[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 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.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, controls and tagged , , , , , , , , , , , . Bookmark the permalink.

One Response to Sort partly numeric items in a ComboBox or ListBox in C#

  1. Pingback: Align numeric values in ComboBox and ListBox controls in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *