轻松学习C#的哈希表

2019-12-30 11:09:15丽君

输出的结果为:添加前al的元素个数为:0

添加后al的元素个数为:3

删除C后al的元素个数为:2

三、Hashtable元素的遍历

遍历哈希表需要用到DictionaryEntry(字典键/值对)Object。

例三、利用foreach语句对哈希表进行遍历

 

 
  1. <span style="font-size:18px;">using System;   using System.Collections;//需要添加的命名空间  
  2. using System.Collections.Generic;   using System.Linq;  
  3. using System.Text;   using System.Threading.Tasks;  
  4.   namespace 哈希表  
  5. {   class Program  
  6. {   static void Main(string[] args)  
  7. {   Hashtable al = new Hashtable();  
  8. Console.WriteLine("添加前al的元素个数为:"+al.Count);   al.Add("1", "a");  
  9. al.Add("2", "b");   al.Add("3", "c");  
  10. Console.WriteLine("添加后al的元素个数为:"+al.Count);   foreach (DictionaryEntry t in al)  
  11. {   Console.Write("键位:"+t.Key+" 值为:");  
  12. Console.WriteLine(t.Value);   }  
  13. Console.ReadLine();   }  
  14. }   }</span>  

输出的结果为:添加前al的元素个数为:0

添加后al的元素个数为:3

键位:1 值为:a

键位:2 值为:b