是否可以对HashTable进行排序?

use*_*740 14 c# sorting hashtable

我有一个返回的属性HashTable.我想在不重构我的财产的情况下对其进行排序.请注意:我不想退回其他类型.码:

    /// <summary>
    /// All content containers.
    /// </summary>
    public Hashtable Containers
    {
        get
        {
            Hashtable tbl = new Hashtable();
            foreach (Control ctrl in Form.Controls)
            {
                if (ctrl is PlaceHolder)
                {
                    tbl.Add(ctrl.ID, ctrl);
                }
                // Also check for user controls with content placeholders.
                else if (ctrl is UserControl)
                {
                    foreach (Control ctrl2 in ctrl.Controls)
                    {
                        if (ctrl2 is PlaceHolder)
                        {
                            tbl.Add(ctrl2.ID, ctrl2);
                        }
                    }
                }
            }

            return tbl;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*lla 18

Hashtables通过将键映射到值来工作.此映射中隐含的概念是密钥未按任何特定顺序排序或存储.

但是,你可以看看SortedDictionary<K,V>.


joe*_*ely 8

另一种选择是像你现在一样构造哈希表,然后简单地从键构造一个有序集.您可以遍历该排序的密钥集,根据需要从哈希表中获取相应的值.


Joe*_*orn 6

lubos是对的:你不能对HashTable进行排序.如果可以的话,它就不会是HashTable.您可以枚举HashTable,然后对枚举进行排序.但那将是非常缓慢的.更好地使用一个SortedDictionary代替.