I need to assign values from a small dictionary collection (10 items) to a larger number (about 20 to 30) of dropdownlists in their selected value property.
Specifically, I need to take the key of the max value in the dictionary, assign it to the first dropdownlist.selected value.
Then take the key of the 2nd highest max value, assign it to the second dropdownlist.
When I go through all the keys/values in the dictionary (and there’s still dropdownlists needing to be assigned), I need to start back at the top using the key of the max value in the dictionary.
I’m able to get the key of the max value like so.
var maxKey =
results
.Aggregate((left, right) => left.Value > right.Value ? left : right).Key;
ddlItem.SelectedValue = maxKey.ToString();
What I was doing originally was, I was removing the maxvalue after assigning it. But I forgot that there would be more dropdownlists than actual dictionary values. I’m guessing the solution is to use a different, temporary collection and work with that? Any help is appreciated.
If using a list is required, how would I transfer a dictionary to a list and use index, key, and value?
You can use
OrderByDescendingto get the key value pairs in descending order by value, egIn this example,
orderedKeyValuePairsis anIOrderedEnumerable<KeyValuePair<int, string>>In order to facilitate assigning to your dropdowns, you could create a utility class that wraps a Queue as follows:
You can use it like this:
In this way, once you get to the end of your ordered list you’ll automatically be back at the start again – the values rotate in a cycle.