簡體   English   中英

如何對KeyValuePair的ComboBox.Items集合進行排序 <string,string> 按價值?

[英]How to sort a ComboBox.Items collection of KeyValuePair<string,string> by Value?

我從服務獲取KeyValuePair,並且某些值未排序,如下所示。

如何通過值求助KeyValuePair,以便它們在ComboBox中按字母順序顯示:

public NationalityComboBox()
{
    InitializeComponent();

    Items.Add(new KeyValuePair<string, string>(null, "Please choose..."));
    Items.Add(new KeyValuePair<string, string>("111", "American"));
    Items.Add(new KeyValuePair<string, string>("777", "Zimbabwean"));
    Items.Add(new KeyValuePair<string, string>("222", "Australian"));
    Items.Add(new KeyValuePair<string, string>("333", "Belgian"));
    Items.Add(new KeyValuePair<string, string>("444", "French"));
    Items.Add(new KeyValuePair<string, string>("555", "German"));
    Items.Add(new KeyValuePair<string, string>("666", "Georgian"));
    SelectedIndex = 0;

}

如果你從服務中獲取它們,我會假設它們在列表中或某種集合中?


如果您使用的是項目列表,則可以使用LINQ擴展方法.OrderBy()對列表進行排序:

 var myNewList = myOldList.OrderBy(i => i.Value); 


如果您將數據作為DataTable獲取,則可以設置表的默認視圖,如下所示:

 myTable.DefaultView.Sort = "Value ASC"; 

當您對ItemsControl (例如ComboBoxListBox ...)進行數據綁定時,您可以使用ICollectionViewInterface管理排序操作。 基本上,您使用CollectionViewSource類檢索實例:

var collectionView = CollectionViewSource.GetDefaultView(this.collections);

然后,您可以使用SortDescription添加排序:

collectionView.SortDescriptions.Add(...)

只需對列表進行預排序:

List<KeyValuePair<string, string>> pairs =
        new List<KeyValuePair<string, string>>( /* whatever */ );

pairs.Sort(
    delegate(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
    {
        return StringComparer.OrdinalIgnoreCase.Compare(x.Value, y.Value);
    }
);

假設從服務返回的集合實現了IEnumerable<T> ,那么你應該能夠做到這樣的事情:

Items.Add(new KeyValuePair<string, string>(null, "Please choose..."));
foreach (var item in collectionReturnedFromService.OrderBy(i => i.Value))
{
    Items.Add(item);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM