日常开发中至于为什么不使用forech遍历字典本站之前已经介绍过,这里就不在赘述了。其实遍历Dictionary除了for循环遍历外,最常用的还有while循环,下面的例子是while遍历Dictionary的用法:

/** 
 *Copyright(C) 2017 by Sorpcboy
 *All rights reserved. 
 *FileName:     Demo.cs
 *Author:       Sorpcboy   
 *Description:  遍历Dictionary的几种方式 
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Demo : MonoBehaviour {
 
    Dictionary<int, string> dic = new Dictionary<int, string>();
 
    Dictionary<int, Dictionary<int,string>> moreDic = new Dictionary<int,Dictionary<int,string>>();
	// Use this for initialization
	void Start ()
    {
        dic.Add(1, "周三");
        dic.Add(2, "林四");
        dic.Add(3, "吴5️");
        moreDic.Add(4, dic);
 
        GetDicData();
        GetMoreDicData();
        GetDicDataList();
    }
 
    /// <summary>
    /// while遍历字典
    /// </summary>
    private void GetDicData()
    {
        var vv = dic.GetEnumerator();
        while (vv.MoveNext())
        {
            print("key:" +vv.Current.Key+"---value:"+vv.Current.Value);
        }
    }
 
    /// <summary>
    /// while遍历多个字典
    /// </summary>
    private void GetMoreDicData()
    {
       
        var vv = moreDic.GetEnumerator();
        while (vv.MoveNext())
        {
            var va = moreDic[vv.Current.Key].GetEnumerator();
            print("moreKey:" +vv.Current.Key);
            while (va.MoveNext())
            {
                print("moreValueKey:" + va.Current.Key + "---moreValueValue:" + va.Current.Value);
            }
        }
    }
 
    /// <summary>
    /// for循环遍历字典
    /// </summary>
    private void GetDicDataList()
    {
        List<int> list = new List<int>(dic.Keys);
        for (int i = 0; i < list.Count; ++i)
        {
            print("ListKey:" +list[i]+"--ListValue:"+dic[list[i]]);
        }
    }
}

有什么意见欢迎进群一起讨论。