遍历

1、使用for遍历字典(Dictionary)

注意:ElementAt()需要引入using System.Linq命名空间,Dictionary命令空间是using System.Collections.Generic;

  1. Dictionary<string, string> dic =
  2. new Dictionary<string, string> {
  3. ["key1"] = "value1",
  4. ["key2"] = "value2",
  5. ["key3"] = "value3"
  6. };
  7. for (int i = 0; i < dic.Count; i++) {
  8. var item = dic.ElementAt (i);
  9. Console.WriteLine ("key is " + item.Key);
  10. Console.WriteLine ("value is " + item.Value);
  11. }
  12. for (int i = 0; i < dic.Count; i++) {
  13. Console.WriteLine ("key is " + dic.Keys.ElementAt (i));
  14. Console.WriteLine ("value is " + dic.Values.ElementAt (i));
  15. }

2、使用foreach遍历字典(Dictionary)

  1. Dictionary<string, string> dic =
  2. new Dictionary<string, string> {
  3. ["key1"] = "value1",
  4. ["key2"] = "value2",
  5. ["key3"] = "value3"
  6. };
  7. foreach (string key in dic.Keys) {
  8. Console.WriteLine ("key is " + key);
  9. Console.WriteLine ("value is " + dic[key]);
  10. }
  11. foreach (string value in dic.Values) {
  12. Console.WriteLine ("value is " + value);
  13. }
  14. foreach (KeyValuePair<string, string> item in dic) {
  15. Console.WriteLine ("key is " + item.Key);
  16. Console.WriteLine ("value is " + item.Value);
  17. }

3、使用while遍历字典(Dictionary)

  1. Dictionary<string, string> dic =
  2. new Dictionary<string, string> {
  3. ["key1"] = "value1",
  4. ["key2"] = "value2",
  5. ["key3"] = "value3"
  6. };
  7. var enumerator = dic.GetEnumerator ();
  8. while (enumerator.MoveNext ()) {
  9. Console.WriteLine ("key is " + enumerator.Current.Key);
  10. Console.WriteLine ("value is " + enumerator.Current.Value);
  11. }

遍历Dictionary并修改Value

在 foreach 中修改Dictionary中的值是不允许的,可以将key 先放在List中,foreach 这个list ,找到需要修改的项后,再修改原Dic中的内容。
示例:修改字典所有value

  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. public class NewBehaviourScript : MonoBehaviour
  4. {
  5. Dictionary<string, int> dic = new Dictionary<string, int>();
  6. void Start()
  7. {
  8. dic.Add("siki", 12);
  9. dic.Add("tom", 22);
  10. List<string> list = new List<string>();
  11. list.AddRange(dic.Keys);
  12. foreach (var child in list)
  13. {
  14. dic[child] = 25;
  15. }
  16. foreach (var child in dic)
  17. {
  18. Debug.Log(child.Key + " " + child.Value);
  19. }
  20. }
  21. }