2009-10-05 96 views
4

我從服務獲得一個KeyValuePair,其中一些值未進行排序,如下所示。如何根據Value對KeyValuePair <string,string>的ComboBox.Items集合進行排序?

我如何通過價值勝地KeyValuePair讓他們按字母順序排列的組合框顯示:

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; 

} 
+1

服務如何將數據返回給您?一本字典?數組?一個列表?一個單獨的對象的負載? – LukeH 2009-10-05 14:34:07

+0

抱歉:集合是KeyValuePair 對象的System.Windows.Controls.ItemCollection。 – 2009-10-05 14:44:33

回答

11

如果您是從服務讓他們,我認爲他們是在一個列表或一組排序?


如果您正在使用的項目列表,你可以將用戶的LINQ擴展方法 .OrderBy()到列表進行排序:

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


如果你所得到的數據作爲一個DataTable,你可以設置該表的默認視圖是這樣的:

myTable.DefaultView.Sort = "Value ASC"; 
2

只需預先排序與列表:

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); 
    } 
); 
+0

謝謝,這很好,適用於我的示例,但在應用程序中,我最終使用了John的OrderBy。 – 2009-10-05 14:54:00

3

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

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

那麼你可以添加排序使用SortDescription:

collectionView.SortDescriptions.Add(...) 
2

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

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