[英]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 文件,當找到 name == CardID 時,它被添加到組合框“cb_card”項中。
...
if (name == "CardID")
{
if (!mainWindow.cb_card.Items.Contains(value))
{
mainWindow.cb_card.Items.Add(value);
}
}
...
我試圖:
Sorted = "true"
但出現錯誤:XLS0413 The property 'Sorted' was not found in type 'ComboBox'.
...
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);
}
...
但訂單與未訂購時相同。
我嘗試了最后一個代碼的一些變體,通過將字符串列表轉換為雙倍,對其進行排序並將其重新轉換為字符串,但我遇到了很多錯誤,我無法用我目前的知識進行調試。
非常感謝您的時間和提前幫助。
您可以為此使用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));
比較兩個項目時,比較返回
這就是為什么從 a 中減去 b 會導致比較的正確結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.