简体   繁体   中英

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;

}

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"; 

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(...)

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);
    }
);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM