I have a Dictionary<string, Func<string, string>>
. I use the keys to provide the items of a drop-down which allows the user to select which algorithm to run. Then I can conveniently feed the selected value back into the dictionary to get the relevant function.
// Initialization
my_dict["Function #1"] = func1;
my_dict["Function #2"] = func2;
...
// Executing
result = my_dict[user_choice](input);
Now, when populating the drop down (a System.Windows.Forms.ComboBox
) I loop through the keys of this with foreach
. MSDN warns that System.Collections.Generic.Dictionary
is not guaranteed to have a stable order. But in practice I know that the order is pretty stable, so it works for now. I do want the functions to be ordered nicely for the user.
However, I want to do this correctly - ie. by using a data structure that guarantees order stability. Unfortunately OrderedDictionary
is not helpful, since it forces the values to be object
s; I'd like to keep them function delegates. At the same time, I don't want to add too much needless complexity (for instance, I could store a copy of the keys as a List<string>
to use for order, but that seems like a poor solution).
What can I do?
Note: Looks like some people assumed that I want my items to be in alphabetical order. I don't. I want them to stay in the same order that I added them in. That is, if key Function #2
is added before Function #1
, it will come before it in the order.