如何对添加到组合框的一组数字字符串进行排序? C#

How to sort a numeric set of strings that are added to a combobox? C#

我想按升序显示添加到组合框的字符串(数字)列表。该项目在 .NET 4.7.2

我有一个数字字符串列表,例如: {“3.453”,“1.123”,“2.024”,“1.567”}

我希望当这些显示在我的组合框中时,它们会按顺序出现: {,"1.123","1.567","2.024","3.453"}

这些值来自读取多个 XML 文件,当找到名称 == CardID 时,它被添加到组合框“cb_card”项中。

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

我尝试过:

  1. 设置组合框属性Sorted = "true" 但出现错误:
XLS0413 The property 'Sorted' was not found in type 'ComboBox'. 
  1. 我尝试将值添加到列表中,然后对列表进行排序,最后将它们添加到组合框中。我编辑了上面显示的代码:
...
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);
}
...

但订单与未订购时保持一致。

我尝试了最后一段代码的一些变体,通过将字符串列表转换成双倍,对其进行排序并将其重新转换为字符串,但是我遇到了很多错误,我无法用我目前的知识进行调试。

  1. 我尝试将值添加到数组而不是列表,对数组进行排序并添加值,但随后组合框显示为空。

非常感谢您的宝贵时间和提前帮助。

您可以为此使用 List.Sort。如果您确定该列表仅包含可以解析为小数(或双精度,...)的数值,则可以使用自定义排序比较,在比较它们之前将字符串转换为小数:

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));

比较两个项目时,比较returns

  • 小于0:a小于b
  • 0: a == b
  • 大于0:a大于b

这就是为什么从 a 中减去 b 导致比较结果正确的原因。