您的位置:首页 > 其它

简单介绍一下字典的遍历

2017-11-20 11:57 375 查看
大家可能都知道字典这种数据结构吧!但是对于字典的遍历都清楚吗?

下面就提供几种方法吧!不说多了,直接来代码吧!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ExampleTest : MonoBehaviour
{
//如何遍历一个字典的四种方式

// Use this for initialization
void Start()
{
Dictionary<string, int> list = new Dictionary<string, int>();
list.Add("LY", 1);
list.Add("YZY", 2);
list.Add("YM", 3);
list.Add("YZLY", 4);

foreach (var item in list)
{
Debug.Log(item.Key + item.Value);
}

//使用KeyValuePair<T,K>
foreach (KeyValuePair<string, int> kv in list)
{
Debug.Log(kv.Key + kv.Value);
}

//通过键的集合取值
foreach (string key in list.Keys)
{
Debug.Log(key + list[key]);
}

//直接取值
foreach (var val in list.Values)
{
Debug.Log(val);
}

//for循环
List<string> test = new List<string>(list.Keys);
for (int i = 0; i < list.Count; i++)
{
Debug.Log(test[i] + list[test[i]]);
}

}

}


世界上没有十全十美的东西,这几种遍历方式都各有千秋!大家自己体会吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: