Home > Back-end >  How to sort a numeric set of strings that are added to a combobox? C#
How to sort a numeric set of strings that are added to a combobox? C#

Time:05-12

I want to display in ascendent order a list of string (numbers) that is added to a combobox. The project is in .NET 4.7.2

I have a string list of numbers such as: {"3.453","1.123","2.024","1.567"}

and I would like that when these are displayed in my combobox they appear in order : {,"1.123","1.567","2.024","3.453"}

The values come from reading multiple XML files and when the name == CardID is found it is added to the combobox "cb_card" items.

...
 if (name == "CardID")
                {
                    if (!mainWindow.cb_card.Items.Contains(value))
                    {
                        mainWindow.cb_card.Items.Add(value);
                    }
                } 
...

I have tried to:

  1. Set the Combobox property Sorted = "true" but an error appears:
XLS0413 The property 'Sorted' was not found in type 'ComboBox'. 
  1. I tried to add the values to a list, then sort the list and finally add them to the combobox. I edited the code shown above:
...
List<string> sortedCardId = new List<string>();
 if (name == "CardID")
                {
                    if (!mainWindow.cb_card.Items.Contains(value))
                    {
                      sortedCardId.Add();  
                    }
                } 

sortedCardId.Sort();
foreach (string ID in sortedCardId)
{
    mainWindow.cb_card.Items.Add(ID);
}
...

but the order stayed the same as when it is nor ordered.

I tried some variants of this last code, by converting the string list in doubled, sort it and reconvert it ot string, but I got to many errors qhich I couldn't debugg with my current knowledge.

  1. I tried to add the values to an array instad of a list, sort the array and add the values, but then the combobox appeared empty.

thanks a lot for your time and help in advance .

CodePudding user response:

You can use List.Sort for this. If you are sure that the list contains only numeric values that can be parsed as a decimal (or double, ...), you can use a custom sort comparison that converts the strings to a decimal before comparing them:

var lst = new List<string>() {"3.453","1.123","2.024","1.567"};
lst.Sort((string a, string b) => (int)(decimal.Parse(a) - decimal.Parse(b)));
// This writes the list content as "1.123, 2.024, 1.567, 3.453"
Console.WriteLine(string.Join(", ", lst));

When comparing two items, the comparison returns

  • less than 0: a is smaller than b
  • 0: a == b
  • greater than 0: a is bigger than b

This is why subtracting b from a leads to a correct result of the comparison.

  • Related