using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Dictionary键值对
{

    class Program
    {
        static void Main(string[] args)
        {
            DicSample1();
            DicSample2();
            DicSample3();
            DicSample4();

            Console.Read();
        }

        //1、用法1: 常规用
        //  增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法
        public static void DicSample1()
        {
            Dictionary<String, String> pList = new Dictionary<String, String>();
            try
            {
                if (pList.ContainsKey("Item1") == false)
                {
                    pList.Add("Item1", "ZheJiang");
                }
                if (pList.ContainsKey("Item2") == false)
                {
                    pList.Add("Item2", "ShangHai");
                }
                else
                {
                    pList["Item2"] = "ShangHai";
                }
                if (pList.ContainsKey("Item3") == false)
                {
                    pList.Add("Item3", "BeiJiang");
                }

            }
            catch (System.Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }

            //判断是否存在相应的key并显示
            if (pList.ContainsKey("Item1"))
            {
                Console.WriteLine("Output: " + pList["Item1"]);
            }

            //遍历Key
            foreach (var key in pList.Keys)
            {
                Console.WriteLine("Output Key: {0}", key);
            }

            //遍历Value
            foreach (String value in pList.Values)
            {
                Console.WriteLine("Output Value: {0}", value);
            }
            //遍历Key和Value
            foreach (var dic in pList)
            {
                Console.WriteLine("Output Key : {0}, Value : {1} ", dic.Key, dic.Value);
            }
        }

        //2、用法2:Dictionary的Value为一个数组
        /// <summary>
        /// Dictionary的Value为一个数组
        /// </summary>
        public static void DicSample2()
        {
            Dictionary<String, String[]> dic = new Dictionary<String, String[]>();
            String[] ZheJiang = { "Huzhou", "HangZhou", "TaiZhou" };
            String[] ShangHai = { "Budong", "Buxi" };
            dic.Add("ZJ", ZheJiang);
            dic.Add("SH", ShangHai);
            Console.WriteLine("Output :" + dic["ZJ"][0]);
        }

        //3、用法3: Dictionary的Value为一个类
        //Dictionary的Value为一个类
        public static void DicSample3()
        {
            Dictionary<String, Student> stuList = new Dictionary<String, Student>();
            Student stu = null;
            for (int i = 0; i < 3; i++)
            {
                stu = new Student();
                stu.Name = i.ToString();
                stu.Name = "StuName" + i.ToString();
                stuList.Add(i.ToString(), stu);
            }

            foreach (var student in stuList)
            {
                Console.WriteLine("Output : Key {0}, Num : {1}, Name {2}", student.Key, student.Value.Name, student.Value.Name);
            }
        }

        //4 备注:Dictionary的扩展方法使用
        /// <summary>
        /// Dictionary的扩展方法使用
        /// </summary>
        public static void DicSample4()
        {
            //1)普通调用
            Dictionary<int, String> dict = new Dictionary<int, String>();
            DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan");
            DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu");
            DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu");
            DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu");
            DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi");

            //2)TryAdd 和 AddOrReplace 这两个方法具有较强自我描述能力,用起来很省心,而且也简单:
            dict.AddOrPeplace(20, "Orange");
            dict.TryAdd(21, "Banana");
            dict.TryAdd(22, "apple");

            //3)像Linq或jQuery一样连起来写
            dict.TryAdd(10, "Bob")
                .TryAdd(11, "Tom")
                .AddOrPeplace(12, "Jom");

            //4) 获取值
            String F = "Ba";
            dict.TryGetValue(31, out F);
            Console.WriteLine("F : {0}", F);

            foreach (var dic in dict)
            {
                Console.WriteLine("Output : Key : {0}, Value : {1}", dic.Key, dic.Value);
            }
            //5)下面是使用GetValue获取值
            var v1 = dict.GetValue(111, null);
            var v2 = dict.GetValue(10, "abc");

            //6)批量添加
            var dict1 = new Dictionary<int, int>();
            dict1.AddOrPeplace(3, 3);
            dict1.AddOrPeplace(5, 5);

            var dict2 = new Dictionary<int, int>();
            dict2.AddOrPeplace(1, 1);
            dict2.AddOrPeplace(4, 4);
            dict2.AddRange(dict1, false);
        }
    }

    //Student类:
    public class Student
    {
        public String Num { get; set; }
        public String Name { get; set; }
    }

    //扩展方法所在的类
    public static class DictionaryExtensionMethodClass
    {
        /// <summary>
        /// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常
        /// </summary>
        public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
        {
            if (dict.ContainsKey(key) == false)
                dict.Add(key, value);
            return dict;
        }

        /// <summary>
        /// 将键和值添加或替换到字典中:如果不存在,则添加;存在,则替换
        /// </summary>
        public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
        {
            dict[key] = value;
            return dict;
        }

        /// <summary>
        /// 获取与指定的键相关联的值,如果没有则返回输入的默认值
        /// </summary>
        public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
        {
            return dict.ContainsKey(key) ? dict[key] : defaultValue;
        }

        /// <summary>
        /// 向字典中批量添加键值对
        /// </summary>
        /// <param name="replaceExisted">如果已存在,是否替换</param>
        public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
        {
            foreach (var item in values)
            {
                if (dict.ContainsKey(item.Key) == false || replaceExisted)
                    dict[item.Key] = item.Value;
            }
            return dict;
        }
    }
}

Dictionary<k,v>键值对的使用的更多相关文章

  1. C#基础精华03(常用类库StringBuilder,List<T>泛型集合,Dictionary<K , V> 键值对集合,装箱拆箱)

    常用类库StringBuilder StringBuilder高效的字符串操作 当大量进行字符串操作的时候,比如,很多次的字符串的拼接操作. String 对象是不可变的. 每次使用 System. ...

  2. 10集合:List<T>,Dictionary<K,V>

    List<T>泛型集合 List<T>是C#中一种快捷.易于使用的泛型集合类型,使用泛型编程为编写面向对象程序增加了极大的效率和灵活性.   1.List<T>用法 ...

  3. 键值对集合Dictionary<K,V>根据索引提取数据

    Dictionary<K,V>中ToList方法返回 List<KeyValuePair<K,V>>定义可设置检索的键/值对

  4. C#泛型集合之Dictionary<k, v>使用技巧

    1.要使用Dictionary集合,需要导入C#泛型命名空间 System.Collections.Generic(程序集:mscorlib) 2.描述 1).从一组键(Key)到一组值(Value) ...

  5. C#泛型集合—Dictionary<K,V>使用技巧

    转载:http://blog.csdn.net/a125138/article/details/7742022 1.要使用Dictionary集合,需要导入C#泛型命名空间 System.Collec ...

  6. 泛型集合List<T> Dictionary<K,V>

    List<T>类似于ArrayList,ArrayList的升级版. 各种方法:Sort().Max().Min().Sum()…   Dictionary<K,V>类似于Ha ...

  7. 转载C#泛型集合—Dictionary<K,V>使用技巧

    1.要使用Dictionary集合,需要导入C#泛型命名空间 System.Collections.Generic(程序集:mscorlib) 2.描述 1).从一组键(Key)到一组值(Value) ...

  8. 基础才是重中之重~Dictionary<K,V>里V的设计决定的性能

    回到目录 字典对象Dictionary<K,V>我们经常会用到,而在大数据环境下,字典使用不当可能引起性能问题,严重的可能引起内在的溢出! 字典的值建议为简单类型,反正使用Tuple< ...

  9. 随笔4 Dictionary<K,V>

    本来说是想介绍一下Hashtable的,但是发现HashMap和Hashtable最开始的不同就是在于HashMap继承了AbstractMap,而Hashtable继承了Dictionary< ...

随机推荐

  1. SpringMVC之控制器的单例和多例管理

    版权声明:本文为博主原创文章,未经博主允许不得转载. 在使用Spring3对控制器Controller进行bean管理时,如果要对控制器是否单例进行管理. 有两种方式配置多例模式: 1.springX ...

  2. centos查看实时网络带宽占用情况方法

    Linux中查看网卡流量工具有iptraf.iftop以及nethogs等,iftop可以用来监控网卡的实时流量(可以指定网段).反向解析IP.显示端口信息等. centos安装iftop的命令如下: ...

  3. [Silverlight]监听指定控件(FrameworkElement)的依赖属性(DependencyProperty)的更改

    前言 转载请注明出处:http://www.cnblogs.com/ainijiutian 最近在silverlight项目使用Telerik的控件,遇到一个问题.就是使用RadBusyIndicat ...

  4. wex5 实战 HeidiSQL 导入Excel数据

    一 前言 以前没做过大东西,突然客户说,我给你个数据,你部署到云上.我想,很简单啊,随口答应了. 悲剧发生了,客发给我的,居然是一张excel表!!! 本来想一条一条数据复制,一看,2000多条!! ...

  5. 【单点登录】【两种单点登录类型:SSO/CAS、相同一级域名的SSO】

    单点登录:SSO(Single Sign On) 什么是单点登录:大白话就是多个网站共享一个用户名和密码的技术,对于普通用户来说,只需要登录其中任意一个网站,登录其他网站的时候就能够自动登陆,不需要再 ...

  6. if语句的一个小技巧

    也就是说选中类型的时候边框属性的选择项是不能选择的一般用if else 在类型的CHANGE方法中,现在一句话就能搞定看代码 private void m_rdbtnProID2_CheckedCha ...

  7. Prince2七大流程之项目准备

    Prince2七大流程之项目准备     今天我们正式进入七大流程的第一个流程学习,项目准备流程.决定项目是否值得做,是否值得启动.通过回答"是否有一个可交付的.值得做的项目?"这 ...

  8. 如何站在使用者的角度来设计SDK-微信公众号开发SDK(消息处理)设计之抛砖引玉

    0.SDK之必备的基本素质 在项目中免不了要用到各种各样的第三方的sdk,在我现在的工作中就在公司内部积累了各种各样的的公共库(基于.net的,基于silverlight的等等),托管到了内部的nug ...

  9. DirectDraw创建Windows窗口

    KWindow.h  KWindow.cpp KDDrawWindow.cpp #define STRICT #define WIN32_LEAN_AND_MEAN #include <wind ...

  10. 开发工具&环境

    远程拷贝:scp cdh4.tar.gz root@10.239.44.111 ~ gerrit for code review: git add . git commit -a git push o ...