Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

How can I resort the KeyValuePair by value so that they display in alphabetical order in the 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;

}
like image 958
Edward Tanguay Avatar asked Dec 02 '22 07:12

Edward Tanguay


1 Answers

If you are getting them from a service, I assume that they are in a list or a set of some sort?


If you are using a list of items, you can user the LINQ Extension Method .OrderBy() to sort the list:
var myNewList = myOldList.OrderBy(i => i.Value);


If you are getting the data as a DataTable, you can set the default view of the table like this:
myTable.DefaultView.Sort = "Value ASC";
like image 64
John Gietzen Avatar answered Dec 19 '22 01:12

John Gietzen