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

一、前言#

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

二、字典的基本使用

 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();
 }

            // 定义
            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);
// 添加存在的元素
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.");

参数为其它类型

// 参数为其它类型 
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]);

参数为自定义类型

// 首先定义类
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);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值