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

[转载]C# HashTable 遍历与排序
        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);
            }

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


原文地址:http://blog.csdn.net/zhenniubile/article/details/6079547

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

上一篇:14. 区间相交


下一篇:C#代码示例_调试