zoukankan      html  css  js  c++  java
  • C#中泛型之Dictionary

    1、命名空间:
    System.Collections.Generic(程序集:mscorlib)
    2、描述:
      1)、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
       2)、任何键都必须是唯一的
       3)、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
       4)、Key和Value可以是任何类型(string,int,custom class 等)
    3、创建及初始化:
    Dictionary<intstring> myDictionary = new Dictionary<intstring>();
    4、添加元素:
    myDictionary.Add("C#",0);
    myDictionary.Add("C++",1);
    myDictionary.Add("C",2);
    myDictionary.Add("VB",2);
    5、查找元素By Key:
      if(myDictionary.ContainsKey("C#"))
      {
        Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
      }
    6.遍历元素 By KeyValuePair
      foreach (KeyValuePair<string, int> kvp in myDictionary)
      {
        Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
      }
    7、仅遍历键 By Keys 属性:
      Dictionary<string, int>.KeyCollection keyCol = myDictionary.Keys;
      foreach (string key in keyCol/*string key in myDictionary.Keys*/)
      {
        Console.WriteLine("Key = {0}", key);
      }
    8、仅遍历值By Valus属性:
      Dictionary<string, int>.ValueCollection valueCol = myDictionary.Values;
      foreach (int value in valueCol)
      {
        Console.WriteLine("Value = {0}", value);
      }
    9.移除指定的键值By Remove方法:
      myDictionary.Remove("C#");
      if (myDictionary.ContainsKey("C#"))
      {
        Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
      }
      else
      {
        Console.WriteLine("不存在 Key : C#");
     

  • 相关阅读:
    vc6编译64位程序
    WebBrowser 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
    python中subprocess.Popen的使用
    对AutoResetEvent和ManualResetEvent的理解
    Vue-Socket.io跨域问题 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' Mentalflow解决思路
    如何使用GoLand debug
    Python协程与JavaScript协程的对比
    [基础] TCP小结
    导出字段脚本
    永恒之蓝——windows server 2003 漏洞
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3569035.html
Copyright © 2011-2022 走看看