C# 基础之字典——Dictionary(一)

一、前言#

对于C#中的Dictionary类相信大家都不陌生,这是一个Collection(集合)类型,可以通过Key/Value(键值对 的形式来存放数据;该类最大的优点就是它查找元素的时间复杂度接近O(1),实际项目中常被用来做一些数据的本地缓存,提升整体效率。

二、字典的基本使用

cs 复制代码
 static void Main(string[] args)
 {
     // 1.定义
     // Key和Value可以是任意类型
     Dictionary<int, string> _testDic = new Dictionary<int, string>();

     // 2.添加元素
     _testDic.Add(24, "Canon");
     // 注意相同相同Key值只能Add一次
     _testDic.Add(24, "Jason");// 报错:System.ArgumentException:"已添加了具有相同键的项。"
                               // 可以使用ContainsKey判断字典中是否已经存在
     if (!_testDic.ContainsKey(24)) _testDic.Add(24, "Canon");

     // 3.删除元素
     // Remove 删除不存在的值不会报错
     _testDic.Remove(24);

     // 4.取值
     // 索引器取值,若字典中没有Key会报错
     string str = _testDic[24];
     // TryGetValue 取值成功返回true,内部对str赋值,否则返回false
     bool isExist = _testDic.TryGetValue(24, out str);

     // 5.改值
     // 要确保字典中确实存在该值
     if (_testDic.ContainsKey(1)) _testDic[1] = "";

     // 6.遍历
     // Key
     foreach (var key in _testDic.Keys) Console.WriteLine("Key = {0}", key);
     // Value
     foreach (var value in _testDic.Values) Console.WriteLine("value = {0}", value);
     // foreach遍历
     foreach (var kvp in _testDic) Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
     // 迭代器遍历
     var enumerator = _testDic.GetEnumerator();
     while (enumerator.MoveNext())
     {
         var kvp = enumerator.Current;
         Console.WriteLine("Key = {0}", kvp.Key);
         Console.WriteLine("Key = {0}", kvp.Value);
     }

     // 7.清空
     _testDic.Clear();
 }
cs 复制代码
            // 定义
            Dictionary<string, string> dictExecutes = new Dictionary<string, string>();

            // 添加元素
            dictExecutes.Add("bmp", "paint.exe");
            dictExecutes.Add("dib", "paint.exe");
            dictExecutes.Add("rtf", "wordpad.exe");
            dictExecutes.Add("txt", "notepad.exe");

            // 取值
            Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

            // 改值
            dictExecutes["rtf"] = "winword.exe";
            Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

            // 遍历 KEY
            foreach (string key in dictExecutes.Keys) Console.WriteLine("Key = {0}", key);

            // 遍历 VALUE
            foreach (string value in dictExecutes.Values) Console.WriteLine("value = {0}", value);

            // 遍历字典
            foreach (KeyValuePair<string, string> kvp in dictExecutes) Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
cs 复制代码
// 添加存在的元素
try{
    dictExecutes.Add("txt", "winword.exe");
}catch( ArgumentException ){
    Console.WriteLine("An element with Key = 'txt' already exists.");
}

// 删除元素
dictExecutes.Remove("doc");
if( !dictExecutes.ContainsKey("doc") ) Console.WriteLine("Key 'doc' is not found.");

// 判断键存在
if( openWith.ContainsKey("bmp") ) Console.WriteLine("An element with Key = 'bmp' exists.");

参数为其它类型

cs 复制代码
// 参数为其它类型 
Dictionary<int, string[]> dictOthers = new Dictionary<int, string[]>();
dictOthers.Add(1, "1,11,111".Split(','));
dictOthers.Add(2, "2,22,222".Split(','));
Console.WriteLine(dictOthers[1][2]);

参数为自定义类型

cs 复制代码
// 首先定义类
class DouCube
{
    private int _Code;
    public int Code { get{ return _Code; } set{ _Code = value; } }
    
    private string _Page;
    public string Page { get{ return _Page; } set{ _Page = value; } } 
}

// 声明并添加元素
Dictionary<int, DouCube> MyTypes = new Dictionary<int, DouCube>();
for( int i = 1; i <= 9; i++ ){
    DouCube elem = new DouCube();
    
    elem.Code = i * 100;
    elem.Page = "http://www.doucube.com/" + i.ToString() + ".html";
    
    MyTypes.Add(i, elem);
}

// 遍历元素
foreach( KeyValuePair<int, DouCube> kvp in MyTypes ){
    Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
}
相关推荐
弱冠少年18 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色19 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
一般清意味……31 分钟前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
卑微求AC32 分钟前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
技术无疆41 分钟前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
爱上语文1 小时前
Java LeetCode每日一题
java·开发语言·leetcode
Манго нектар1 小时前
JavaScript for循环语句
开发语言·前端·javascript
程序猿小D2 小时前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa
阿华的代码王国2 小时前
【JavaEE】——文件IO的应用
开发语言·python