遍历Dictionary的几种方式

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/** 
*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]]);
}
}
}

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