views:

587

answers:

4

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;

}
+5  A: 

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";
John Gietzen
+1  A: 

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);
   }
  );
csharptest.net
thanks, this is nice, works on my example, but in the application I ended up using John's OrderBy.
Edward Tanguay
+1  A: 

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:

var collectionView = CollectionViewSource.GetDefaultView(this.collections);

Then you can add sort using the SortDescription:

collectionView.SortDescriptions.Add(...)

Jalfp
A: 

Assuming that the collection returned from the service implements IEnumerable<T>, then you should be able to do something like this:

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