Search code examples
c#sortinghashtable

Is it possible to sort a HashTable?


I have a property that returns a HashTable. I would like to sort it without refactoring my property. Please note: I do not want to return another type. Code:

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

Solution

  • Another option is to construct the hash table as you're already doing, and then simply construct a sorted set from the keys. You can iterate through that sorted key set, fetching the corresponding value from the hash table as needed.