DoubleMap.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using System;
  2. using System.Collections.Generic;
  3. namespace KYFramework
  4. {
  5. public class DoubleMap<K, V>
  6. {
  7. private readonly Dictionary<K, V> kv = new Dictionary<K, V>();
  8. private readonly Dictionary<V, K> vk = new Dictionary<V, K>();
  9. public DoubleMap()
  10. {
  11. }
  12. public DoubleMap(int capacity)
  13. {
  14. kv = new Dictionary<K, V>(capacity);
  15. vk = new Dictionary<V, K>(capacity);
  16. }
  17. public void ForEach(Action<K, V> action)
  18. {
  19. if (action == null)
  20. {
  21. return;
  22. }
  23. Dictionary<K, V>.KeyCollection keys = kv.Keys;
  24. foreach (K key in keys)
  25. {
  26. action(key, kv[key]);
  27. }
  28. }
  29. public List<K> Keys
  30. {
  31. get
  32. {
  33. return new List<K>(kv.Keys);
  34. }
  35. }
  36. public List<V> Values
  37. {
  38. get
  39. {
  40. return new List<V>(vk.Keys);
  41. }
  42. }
  43. public void Add(K key, V value)
  44. {
  45. if (key == null || value == null || kv.ContainsKey(key) || vk.ContainsKey(value))
  46. {
  47. return;
  48. }
  49. kv.Add(key, value);
  50. vk.Add(value, key);
  51. }
  52. public V GetValueByKey(K key)
  53. {
  54. if (key != null && kv.ContainsKey(key))
  55. {
  56. return kv[key];
  57. }
  58. return default(V);
  59. }
  60. public K GetKeyByValue(V value)
  61. {
  62. if (value != null && vk.ContainsKey(value))
  63. {
  64. return vk[value];
  65. }
  66. return default(K);
  67. }
  68. public void RemoveByKey(K key)
  69. {
  70. if (key == null)
  71. {
  72. return;
  73. }
  74. V value;
  75. if (!kv.TryGetValue(key, out value))
  76. {
  77. return;
  78. }
  79. kv.Remove(key);
  80. vk.Remove(value);
  81. }
  82. public void RemoveByValue(V value)
  83. {
  84. if (value == null)
  85. {
  86. return;
  87. }
  88. K key;
  89. if (!vk.TryGetValue(value, out key))
  90. {
  91. return;
  92. }
  93. kv.Remove(key);
  94. vk.Remove(value);
  95. }
  96. public void Clear()
  97. {
  98. kv.Clear();
  99. vk.Clear();
  100. }
  101. public bool ContainsKey(K key)
  102. {
  103. if (key == null)
  104. {
  105. return false;
  106. }
  107. return kv.ContainsKey(key);
  108. }
  109. public bool ContainsValue(V value)
  110. {
  111. if (value == null)
  112. {
  113. return false;
  114. }
  115. return vk.ContainsKey(value);
  116. }
  117. public bool Contains(K key, V value)
  118. {
  119. if (key == null || value == null)
  120. {
  121. return false;
  122. }
  123. return kv.ContainsKey(key) && vk.ContainsKey(value);
  124. }
  125. }
  126. }