学习Key与Value的集合hashtable

你可以创建一个hashtable:

 

你可以使用foreach方法,把hashtable的key与value循环写出来:

 

在控制台屏幕输出:

 

如果只需把key输出:

 

如果只想把值循环输出:

 

测试输出结果:

 

 

往hashtable集合添加key与value:

 

有添加就是移除:

 

测试上面的添加Add和移除:

 

key值为"A"已经被移除。

 

接下来,再练习2个方法,就是判断key或avlue是否已经存在集合:

完整练习代码:

 class Av
    {
        public Hashtable HashtableEntity = new Hashtable()
        {
            { "A", "Leo" },
            { "B", "Insus.NET" },
            { "C", "Jack" }
        };


        public void Output()
        {
            foreach (DictionaryEntry de in HashtableEntity)
            {
                Console.WriteLine(string.Format("Key: {0}; Value: {1}", de.Key, de.Value));
            }
        }        

        public void ForeachKey()
        {
            foreach (string key in HashtableEntity.Keys)
            {
                Console.WriteLine(key);
            }
        }

        public void ForeachValue()
        {
            foreach (string value in HashtableEntity.Values)
            {
                Console.WriteLine(value);
            }
        }
        
        public void Add(string key, string value)
        {
            HashtableEntity.Add(key, value);
        }

        public void Remove(string key)
        {
            HashtableEntity.Remove(key);
        }

        public bool isExitByKey(string key)
        {
            return HashtableEntity.ContainsKey(key);
        }

        public bool isExistByValue(string value)
        {
            return HashtableEntity.ContainsValue(value);
        }

    }
Source Code

 

posted @ 2017-12-12 23:47  Insus.NET  阅读(761)  评论(0编辑  收藏  举报