C#初学25 Hashtable哈希表(键值对)

    技术2023-03-26  111

    static void Main(string[] args) { Hashtable hash = new Hashtable(); 键值对集合的“键”一定不能重复。(唯一) hash.Add(1, "飞机"); hash.Add("xyz",new Person() { Name="猪仔"}); 判断一个集合中是否存在某个键 if (hash.ContainsKey("xyz")) { Console.WriteLine("存在"); } 判断键值对中是否存在某个值 if (hash.ContainsValue("飞机")) { Console.WriteLine("存在2"); } 根据键获取值 Console.WriteLine(hash[1].ToString()); Person pp =hash["xyz"] as Person; Console.WriteLine(pp.Name); 遍历Hashtable 1.遍历键 foreach (object item in hash.Keys) { Console.WriteLine("键{0},值{1}",item,hash[item]); } 2.遍历值 foreach (object item in hash.Values) { Console.WriteLine("值:{0}",item); } 3.遍历键值对 foreach (DictionaryEntry kv in hash) { Console.WriteLine("键:{0} 值:{1}",kv.Key,kv.Value); } Console.ReadKey(); }
    Processed: 0.016, SQL: 9