如何保持字典顺序? [英] How to keep a Dictionary ordered?
问题描述
我有一个 Dictionary< string,Func< string,string>>
。我使用键来提供一个下拉菜单项,该菜单项允许用户选择要运行的算法。然后,我可以方便地将所选值反馈到字典中以获得相关功能。
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);
现在,当填充下拉列表时( System.Windows.Forms。 ComboBox
)我用 foreach
遍历了这些键。 MSDN警告: System.Collections.Generic.Dictionary
不能保证顺序稳定。但实际上,我知道顺序非常稳定,因此现在可以使用。我确实希望这些功能能很好地为用户排序。
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.
但是,我想正确地执行此操作-即。通过使用保证订单稳定性的数据结构。不幸的是 OrderedDictionary
并没有帮助,因为它会强制将值设为 object
s;我想让他们担任职能代表。同时,我不想增加太多不必要的复杂性(例如,我可以将键的副本存储为 List< string>
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).
我该怎么办?
注意: 似乎有些人认为我希望我的商品按字母顺序排列。我不。我希望它们保持与添加它们时的顺序相同。也就是说,如果在函数#1之前添加键
函数#2
推荐答案
而不是使用 OrderedDictionary
,则应使用 SortedDictionary< TKey,TValue>
。
Instead of using the OrderedDictionary
, you should use the SortedDictionary<TKey, TValue>
.
此键按键排序。因此,以您的字符串为例。这样就足够了。
This one is sorted by the key. So for your example by your Strings. This should suffice.
如果您未使用任何本地可比较类型,则需要实现 IEqualityComparer< T>
键类的界面。
If you are not using any native comparable type you need to implement the IEqualityComparer<T>
interface for your key-class.
这篇关于如何保持字典顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!