[英]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;
}
如果你從服務中獲取它們,我會假設它們在列表中或某種集合中?
.OrderBy()
對列表進行排序:
var myNewList = myOldList.OrderBy(i => i.Value);
myTable.DefaultView.Sort = "Value ASC";
當您對ItemsControl
(例如ComboBox
, ListBox
...)進行數據綁定時,您可以使用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.