繁体   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