C# 如何对组合框进行排序。KeyValuePair的Items集合<;字符串,字符串>;按价值计算?

C# 如何对组合框进行排序。KeyValuePair的Items集合<;字符串,字符串>;按价值计算?,c#,wpf,sorting,combobox,C#,Wpf,Sorting,Combobox,我从服务中获得一个KeyValuePair,其中一些值没有排序,如下所示 如何按值调用KeyValuePair,以便它们在组合框中按字母顺序显示: public NationalityComboBox() { InitializeComponent(); Items.Add(new KeyValuePair<string, string>(null, "Please choose...")); Items.Add(new KeyValuePair<st

我从服务中获得一个KeyValuePair,其中一些值没有排序,如下所示

如何按值调用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;

}
public NationalityComboBox()
{
初始化组件();
添加(新的KeyValuePair(空,“请选择…”);
添加(新的KeyValuePair(“111”,“美式”));
添加(新的KeyValuePair(“777”,“津巴布韦”));
添加(新的KeyValuePair(“222”,“澳大利亚”));
添加(新的KeyValuePair(“333”,“比利时”));
添加(新的KeyValuePair(“444”,“法语”));
添加(新的KeyValuePair(“555”、“德语”);
添加(新的KeyValuePair(“666”,“格鲁吉亚”));
SelectedIndex=0;
}

如果您从服务中获取它们,我假设它们在列表或某种类型的集合中


如果使用的是项目列表,则可以使用LINQ扩展方法
.OrderBy()
对列表进行排序:

var myNewList = myOldList.OrderBy(i => i.Value);

如果将数据作为DataTable获取,则可以如下设置表的默认视图:

myTable.DefaultView.Sort = "Value ASC";
Items.Add(new KeyValuePair<string, string>(null, "Please choose..."));
foreach (var item in collectionReturnedFromService.OrderBy(i => i.Value))
{
    Items.Add(item);
}

只需使用列表进行预排序:

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);
    }
);
列出对=
新名单(/*随便*/);
成对,分类(
代理(键值对x、键值对y)
{
返回StringComparer.OrdinalIgnoreCase.Compare(x.Value,y.Value);
}
);

当您对
项控件
进行数据绑定时(例如
组合框
列表框
…),您可以使用
ICollectionViewInterface
管理排序操作。基本上,您可以使用
CollectionViewSource
类检索实例:

var collectionView = CollectionViewSource.GetDefaultView(this.collections);
然后可以使用SortDescription添加排序:

collectionView.SortDescriptions.Add(...)

假设从服务返回的集合实现了
IEnumerable
,那么您应该能够执行以下操作:

myTable.DefaultView.Sort = "Value ASC";
Items.Add(new KeyValuePair<string, string>(null, "Please choose..."));
foreach (var item in collectionReturnedFromService.OrderBy(i => i.Value))
{
    Items.Add(item);
}
Items.Add(新的KeyValuePair(null,“请选择…”);
foreach(collectionReturnedFromService.OrderBy(i=>i.Value)中的var项)
{
项目。添加(项目);
}

服务如何将数据返回给您?字典?阵列?名单?加载单独的对象?抱歉:集合是一个System.Windows.Controls.ItemCollection的KeyValuePair对象。谢谢,这很好,适用于我的示例,但在应用程序中,我最终使用了John的OrderBy。