Dictionary 的五种遍历方法

发布时间 2023-10-18 15:21:55作者: juaa
        //3.0以上版本可以使用
 
        //方法一: 通过var类型获取 键 值
        foreach (var item in dic)
        {
            Debug.Log(item.Key + item.Value);
        }
 
        //方法二:使用KeyValuePair<T,K>获取
        foreach (KeyValuePair<string, int> kv in dic)
        {
            Debug.Log(kv.Key + kv.Value);
        }
 
        //方法三:通过键的集合取值
        foreach (string key in dic.Keys)
        {
            Debug.Log(key + dic[key]);
        }
 
        //方法四:直接取值
        foreach (int val in dic.Values)
        {
            Debug.Log(val);
        }
 
        //方法五:使用for循环获取 需要创建List来存储字典Key(键值) 循环key获取值
        List<string> test = new List<string>(dic.Keys);
 
        for (int i = 0; i < dic.Count; i++)
        {
            Debug.Log(test[i] + dic[test[i]]);
        }