• C# Dictionary使用


    Dictionary

    类型:System.Collections.Generic.Dictionary  

    eg:Dictionary<string, int> illegParking = new Dictionary<string, int>();

    键:inData.LOTID

    值:inData.ISILLEGPARKING

    1、判断键存不存在。

    dictionary中是不允许有重复项的,这样才能按key索引到唯一一个value

    if (illegParking.ContainsKey(inData.LOTID))
                    {
                        illegParking[inData.LOTID] = inData.ISILLEGPARKING;
                    }
                    else
                    {
                        illegParking.Add(inData.LOTID, inData.ISILLEGPARKING);
                    }
    
     
    View Code

    2、几种遍历方式:

    Dictionary<string, int> list = new Dictionary<string, int>();
    
       foreach (var item in list)
    
                {
    
                    Console.WriteLine(item.Key + item.Value);
    
                }
    
     //通过键的集合取
    
                foreach (string key in list.Keys)
    
                {
    
                    Console.WriteLine(key + list[key]);
    
                }
    
       //直接取值
    
                foreach (int val in list.Values)
    
                {
    
                    Console.WriteLine(val);
    
                } 
    
     //非要采用for的方法也可
    
     Dictionary<string, int> list = new Dictionary<string, int>();         
    
       List<string> test = new List<string>(list.Keys);
    
                for (int i = 0; i < list.Count; i++)
    
                {
    
                    Console.WriteLine(test[i] + list[test[i]]);
    
                }
    View Code

    3、涉及到移除某个键值的时候

    不能在foreach循环里面移除,因为会导致错误:集合已修改;可能无法执行枚举操作。可以改用for循环

    //dicmodels是个dictionary

    List<string> keys = new List<string>(dicModels.Keys);
    for (int i = keys.Count - 1; i >= 0; i--)
     {
     }

    KeyValuePair 和 Dictionary 的关系和区别

    结构:System.Collections.Generic.KeyValuePair<TKey, TValue>
    1、KeyValuePair 
        a、KeyValuePair 是一个结构体(struct);
        b、KeyValuePair 只包含一个Key、Value的键值对。
    2、Dictionary 
        a、Dictionary 可以简单的看作是KeyValuePair 的集合;
        b、Dictionary 可以包含多个Key、Value的键值对。
  • 相关阅读:
    杨辉三角实现
    三种方式都能生成同样的列表
    Python 直接赋值、浅拷贝和深度拷贝解析
    Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
    教你玩转CSS 分组选择器和嵌套选择器
    教你玩转CSS padding(填充)
    教你玩转CSS 轮廓(outline)属性
    教你玩转CSS margin(外边距)
    教你玩转CSS border(边框)
    教你玩转CSS表格(table)
  • 原文地址:https://www.cnblogs.com/peterYong/p/10881869.html
Copyright © 2020-2023  润新知