C# Dictionary traversal method

Dictionary<int, string> dic = new Dictionary<int, string>() 
{
    {101,"aa.txt"},
    {102,"bb.txt"},
    {103,"cc.txt"}
};

//-- 通过var类型获取 键 值
foreach (var item in dic)
{
    Debug.Log(item.Key + ":" + item.Value);
}
 
//-- 使用KeyValuePair<T,K>获取
foreach (KeyValuePair<int, string> item in dic)
{
    Debug.Log(item.Key + ":" + item.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获取值
//-- 适合对dic修改删除等操作
List<string> keys = new List<string>(dic.Keys);
for (int i = 0; i < dic.Count; i++)
{
    Debug.Log(keys[i] + ":" + dic[keys[i]]);
}

Guess you like

Origin blog.csdn.net/qq_38318701/article/details/128308860