简单介绍一下字典的遍历

来源:互联网 发布:淘宝店铺仓库管理 编辑:程序博客网 时间:2024/06/06 14:14

大家可能都知道字典这种数据结构吧!但是对于字典的遍历都清楚吗?
下面就提供几种方法吧!不说多了,直接来代码吧!

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]]);        }    }}

世界上没有十全十美的东西,这几种遍历方式都各有千秋!大家自己体会吧!

原创粉丝点击