//Hashtable sample System.Collections.Hashtable ht =new System.Collections.Hashtable(); //--Be careful: Keys can't be duplicated, and can't be null---- ht.Add(1, "apple"); ht.Add(2, "banana"); ht.Add(3, "orange"); //Modify item value: if(ht.ContainsKey(1)) ht[1] ="appleBad"; //The following code will return null oValue, no exception object oValue = ht[5]; //traversal 1: foreach (DictionaryEntry de in ht) { Console.WriteLine(de.Key); Console.WriteLine(de.Value); } //traversal 2: System.Collections.IDictionaryEnumerator d = ht.GetEnumerator(); while (d.MoveNext()) { Console.WriteLine("key:{0} value:{1}", d.Entry.Key, d.Entry.Value); } //Clear items ht.Clear();
Dictionary和HashTable内部实现差不多,但前者无需装箱拆箱操作,效率略高一点。
//Dictionary sample System.Collections.Generic.Dictionary<int, string> fruits = new System.Collections.Generic.Dictionary<int, string>(); fruits.Add(1, "apple"); fruits.Add(2, "banana"); fruits.Add(3, "orange"); foreach (int i in fruits.Keys) { Console.WriteLine("key:{0} value:{1}", i, fruits); } if (fruits.ContainsKey(1)) { Console.WriteLine("contain this key."); }
ArrayList是一维变长数组,内部值为object类型,效率一般:
//ArrayList System.Collections.ArrayList list =new System.Collections.ArrayList(); list.Add(1);//object type list.Add(2); for (int i =0; i < list.Count; i++) { Console.WriteLine(list[i]); }