zoukankan      html  css  js  c++  java
  • C#字典 Dictionary 用法

    Dictionary提供快速的基于键值的元素查找。
    结构是:Dictionary <[key] , [value] >,当你有很多元素的时候可以用它。
    它包含在System.Collections.Generic名控件中。在使用前,你必须声明它的键类型和值类型。
    复制代码
     
    1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Demo1 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //创建泛型哈希表,Key类型为int,Value类型为string 14 Dictionary<int, string> myDictionary = new Dictionary<int, string>(); 15 //1.添加元素 16 myDictionary.Add(1, "a"); 17 myDictionary.Add(2, "b"); 18 myDictionary.Add(3, "c"); 19 //2.删除元素 20 myDictionary.Remove(3); 21 //3.假如不存在元素则添加元素 22 if (!myDictionary.ContainsKey(4)) 23 { 24 myDictionary.Add(4, "d"); 25 } 26 //4.显示容量和元素个数 27 Console.WriteLine("元素个数:{0}",myDictionary.Count); 28 //5.通过key查找元素 29 if (myDictionary.ContainsKey(1)) 30 { 31 Console.WriteLine("key:{0},value:{1}","1", myDictionary[1]); 32 Console.WriteLine(myDictionary[1]); 33 } 34 //6.通过KeyValuePair遍历元素 35 foreach (KeyValuePair<int,string>kvp in myDictionary) 36 { 37 Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value); 38 39 } 40 //7.得到哈希表键的集合 41 Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys; 42 //遍历键的集合 43 foreach (int n in keyCol) 44 { 45 Console.WriteLine("key={0}", n); 46 } 47 //8.得到哈希表值的集合 48 Dictionary<int, string>.ValueCollection valCol = myDictionary.Values; 49 //遍历值的集合 50 foreach( string s in valCol) 51 { 52 Console.WriteLine("value:{0}",s); 53 } 54 //9.使用TryGetValue方法获取指定键对应的值 55 string slove = string.Empty; 56 if (myDictionary.TryGetValue(5, out slove)) 57 { 58 Console.WriteLine("查找结果:{0}", slove); 59 } 60 else 61 { 62 Console.WriteLine("查找失败"); 63 } 64 //10.清空哈希表 65 //myDictionary.Clear(); 66 Console.ReadKey(); 67 } 68 } 69 }
    复制代码

    运行结果:

  • 相关阅读:
    POJ 2431 Expedition(探险)
    POJ 3253 Fence Repair(修篱笆)
    POJ 3069 Saruman's Army(萨鲁曼军)
    POJ 3617 Best Cow Line(最佳奶牛队伍)
    [蓝桥杯] 排它平方数
    [蓝桥杯] 小朋友排队
    UVA315 Network 连通图割点
    POJ 1236 Network of Schools 连通图缩点
    poj1061 青蛙的约会
    拓展欧几里
  • 原文地址:https://www.cnblogs.com/wwwbdabc/p/11652579.html
Copyright © 2011-2022 走看看