大家可能都知道字典这种数据结构吧!但是对于字典的遍历都清楚吗?
下面就提供几种方法吧!不说多了,直接来代码吧!
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]]);
}
}
}
字典的简单用法
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DictionaryTest : MonoBehaviour
{
public Dictionary<string, string> dic = new Dictionary<string, string>();
// Use this for initialization
void Start()
{
//添加字典的元素
for (int i = 0; i < 5; i++)
{
dic.Add("key" + i, "value" + i);
}
//遍历字典
foreach (KeyValuePair<string, string> kvp in dic)
{
Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}
//遍历value
foreach (string v in dic.Values)
{
Debug.Log(string.Format("value = {0}", v));
}
//取值
string val = dic["key1"];
// 赋值
dic["key1"] = "new value";
//删除元素
dic.Remove("key1");
if (!dic.ContainsKey("key1"))
{
Debug.Log("Key \"key1\" is not found.");
}
//判断键存在
if (dic.ContainsKey("key1")) // True
{
Debug.Log("An element with Key = \"key1\" exist.");
}
}
}
世界上没有十全十美的东西,这几种遍历方式都各有千秋!大家自己体会吧!