C# 如何按值对 KeyValuePair<string,string> 的 ComboBox.Items 集合进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1520457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a ComboBox.Items collection of KeyValuePair<string,string> by Value?
提问by Edward Tanguay
I'm getting a KeyValuePair from a serviceand 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;
}
采纳答案by John Gietzen
If you are getting them from a service, I assume that they are in a list or a set of some sort?
如果您从服务中获取它们,我假设它们在列表或某种集合中?
如果您使用的是项目列表,则可以使用 LINQ 扩展方法
.OrderBy()
.OrderBy()
对列表进行排序:var myNewList = myOldList.OrderBy(i => i.Value);
如果您将数据作为 DataTable 获取,您可以像这样设置表的默认视图:
myTable.DefaultView.Sort = "Value ASC";
回答by csharptest.net
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);
}
);
回答by japf
When you databind an ItemsControl
(such as a ComboBox
, a ListBox
...), you can manage sort operations using the ICollectionViewInterface
. Basically, you retrieve the instance using the CollectionViewSource
class:
当您对一个ItemsControl
(例如 a ComboBox
、 a ListBox
...)进行数据绑定时,您可以使用ICollectionViewInterface
. 基本上,您可以使用CollectionViewSource
该类检索实例:
var collectionView = CollectionViewSource.GetDefaultView(this.collections);
Then you can add sort using the SortDescription:
然后您可以使用 SortDescription 添加排序:
collectionView.SortDescriptions.Add(...)
回答by LukeH
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);
}