您的位置:首页 > 编程语言 > C#

[转载]C# HashTable 遍历与排序

2014-02-05 13:32 411 查看
private void Form1_Load(object sender, EventArgs e)
{
Hashtable ht = new Hashtable();

ht.Add("job", "a");
ht.Add("jobmon", "20");

//单个取值,方法比较特别
string a = ht["jobmon"].ToString();
//Console.WriteLine(a);

//第一种方法遍历
foreach(DictionaryEntry de in ht)
{
Console.WriteLine(de.Key);
Console.WriteLine(de.Value);
}

Console.WriteLine("-------------------------");

//第二种方法遍历
IDictionaryEnumerator enumerator = ht.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Key);
Console.WriteLine(enumerator.Value);
}

Console.WriteLine("++++++++++++++++++++++++++");
//hashtable的排序第一种方法,按照键的大小排序

ArrayList al = new ArrayList(ht.Keys);

al.Sort();
al.Reverse(); //反向排序

foreach (string str in al)
{
Console.WriteLine(str + "  " + ht[str]);
}

Console.WriteLine("++++++++++++++++++++++++++");
//hashtable的排序第二种方法,按照值的大小排序

ArrayList alv = new ArrayList(ht.Values);
alv.Sort();

foreach (string str in alv)
{
IDictionaryEnumerator enumerator2 = sl.GetEnumerator();

while (enumerator2.MoveNext())
{
if (str.Equals(enumerator2.Value.ToString()))
{

Console.WriteLine(enumerator2.Key + ":" + enumerator2.Value);
}

}

}

Console.WriteLine("++++++++++++++++++++++++++");
//hashtable的排序第三种方法,用SortedList代替hashtable

SortedList sl = new SortedList();

sl.Add("a", "a1");
sl.Add("c", "c1");
sl.Add("b", "b1");

IDictionaryEnumerator enumerator1 = sl.GetEnumerator();
while (enumerator1.MoveNext())
{
Console.WriteLine(enumerator1.Key);
Console.WriteLine(enumerator1.Value);
}

}


原文地址:http://blog.csdn.net/zhenniubile/article/details/6079547
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: