• C# 泛型Dictionary (Hashtable)


    C# 泛型Dictionary (Hashtable)using System;
    using System.Collections.Generic;
    public class Example
    {
        public static void Main()
        {
            //创建泛型哈希表,然后加入元素
            Dictionary<string, string> oscar = new Dictionary<string, string>();
            oscar.Add("哈莉•贝瑞", "《死囚之舞》");
            oscar.Add("朱迪•丹奇", "《携手人生》");
            oscar.Add("尼科尔•基德曼", "《红磨坊》");
            oscar.Add("詹妮弗•康纳利", "《美丽心灵》");
            oscar.Add("蕾妮•齐维格", "《BJ单身日记》");
            //删除元素
            oscar.Remove("詹妮弗•康纳利");
            //假如不存在元素则加入元素
            if (!oscar.ContainsKey("茜茜•斯派克")) oscar.Add("茜茜•斯派克", "《不伦之恋》");
            //显然容量和元素个数
            Console.WriteLine("元素个数: {0}", oscar.Count);
            //遍历集合
            Console.WriteLine("74届奥斯卡最佳女主角及其电影:");
            foreach (KeyValuePair<string, string> kvp in oscar)
            {
                Console.WriteLine("姓名:{0},电影:{1}", kvp.Key, kvp.Value);
            }
            //得到哈希表中键的集合
            Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
            //遍历键的集合
            Console.WriteLine("最佳女主角:");
            foreach (string s in keyColl)
            {
                Console.WriteLine(s);
            }
            //得到哈希表值的集合
            Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
            //遍历值的集合
            Console.WriteLine("最佳女主角电影:");
            foreach (string s in valueColl)
            {
                Console.WriteLine(s);
            }
            //使用TryGetValue方法获取指定键对应的值
            string slove = string.Empty;
            if (oscar.TryGetValue("朱迪•丹奇", out slove))
                Console.WriteLine("我最喜欢朱迪•丹奇的电影{0}", slove);
            else
                Console.WriteLine("没找到朱迪•丹奇的电影");
            //清空哈希表
            oscar.Clear();
            Console.ReadLine();
        }
    }
    
    
    运行效果如下:
    

      

  • 相关阅读:
    nginx 详解
    阿里云 消息队列mq
    手机浏览器Yandex安装插件说明
    windows下JAVA环境变量配置
    共享文件夹免密登入
    自动添加静态路由
    加入WSUS补丁服务器并下载补丁
    加入时间同步服务器(NTP)
    更改rdp端口
    关闭及开启445等危险端口
  • 原文地址:https://www.cnblogs.com/xiaofengfeng/p/2596868.html
Copyright © 2020-2023  润新知