2009-10-05 45 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); 
} 
相关问题