[英]How to sort a ComboBox.Items collection of KeyValuePair<string,string> by Value?
I'm getting a KeyValuePair from a service and some of the values are not sorted, as reproduced below. 我从服务获取KeyValuePair,并且某些值未排序,如下所示。
How can I resort the KeyValuePair by value so that they display in alphabetical order in the ComboBox: 如何通过值求助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;
}
If you are getting them from a service, I assume that they are in a list or a set of some sort? 如果你从服务中获取它们,我会假设它们在列表中或某种集合中?
.OrderBy()
to sort the list:
.OrderBy()
对列表进行排序:
var myNewList = myOldList.OrderBy(i => i.Value);
myTable.DefaultView.Sort = "Value ASC";
When you databind an ItemsControl
(such as a ComboBox
, a ListBox
...), you can manage sort operations using the ICollectionViewInterface
. 当您对
ItemsControl
(例如ComboBox
, ListBox
...)进行数据绑定时,您可以使用ICollectionViewInterface
管理排序操作。 Basically, you retrieve the instance using the CollectionViewSource
class: 基本上,您使用
CollectionViewSource
类检索实例:
var collectionView = CollectionViewSource.GetDefaultView(this.collections);
Then you can add sort using the SortDescription: 然后,您可以使用SortDescription添加排序:
collectionView.SortDescriptions.Add(...)
Just pre-sort with a list: 只需对列表进行预排序:
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);
}
);
Assuming that the collection returned from the service implements IEnumerable<T>
, then you should be able to do something like this: 假设从服务返回的集合实现了
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.