Programming Journal C#, Java, SQL and to a lesser extent HTML, CSS, XML, and regex. I made this so other programmers could benefit from my experience.

Wednesday, October 24, 2007

Reversing the Keys and Values in a Hashtable

Here's how to reverse the Keys and Values in a Hashtable. I use the results and overwrite the original ht.Adds.
The results are output into the TextBox txtReversed.Text


protected void btnReverseHash_Click(object sender, EventArgs e)
{
Hashtable ht = new Hashtable();
ht.Add("a1", "Ask");
ht.Add("a2", "Ask what your country can do for you");
ht.Add("a3", "Ask what you can do for your country");
IDictionaryEnumerator _enum = ht.GetEnumerator();
string sOut = "";
const string _FRONT = "ht.Add(";
const string _END = ");\n";
const string _Q = "\"";
const string _CS = ", ";
while (_enum.MoveNext())
{
sOut += _FRONT + _Q + _enum.Value.ToString() + _Q + _CS
+ _Q + _enum.Key.ToString() + _Q + _END;
}
txtReversed.Text = sOut;
}

No comments: