如何按Value对KeyValuePair的ComboBox.Items集合<string,string>进行排序?

Edw*_*uay 4 c# sorting wpf combobox

我从服务获取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;

}
Run Code Online (Sandbox Code Playgroud)

Joh*_*zen 11

如果你从服务中获取它们,我会假设它们在列表中或某种集合中?


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

var myNewList = myOldList.OrderBy(i => i.Value);
Run Code Online (Sandbox Code Playgroud)


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

myTable.DefaultView.Sort = "Value ASC";
Run Code Online (Sandbox Code Playgroud)