UnOrderMultiMapSet.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /**
  2. * 多重映射结构
  3. *
  4. */
  5. using System.Collections.Generic;
  6. namespace ETModel
  7. {
  8. public class UnOrderMultiMapSet<T, K>
  9. {
  10. private readonly Dictionary<T, HashSet<K>> dictionary = new Dictionary<T, HashSet<K>>();
  11. // 重用HashSet
  12. private readonly Queue<HashSet<K>> queue = new Queue<HashSet<K>>();
  13. public HashSet<K> this[T t]
  14. {
  15. get
  16. {
  17. HashSet<K> set;
  18. if (!this.dictionary.TryGetValue(t, out set))
  19. {
  20. set = new HashSet<K>();
  21. }
  22. return set;
  23. }
  24. }
  25. public Dictionary<T, HashSet<K>> GetDictionary()
  26. {
  27. return this.dictionary;
  28. }
  29. public void Add(T t, K k)
  30. {
  31. HashSet<K> set;
  32. this.dictionary.TryGetValue(t, out set);
  33. if (set == null)
  34. {
  35. set = this.FetchList();
  36. this.dictionary[t] = set;
  37. }
  38. set.Add(k);
  39. }
  40. public bool Remove(T t, K k)
  41. {
  42. HashSet<K> set;
  43. this.dictionary.TryGetValue(t, out set);
  44. if (set == null)
  45. {
  46. return false;
  47. }
  48. if (!set.Remove(k))
  49. {
  50. return false;
  51. }
  52. if (set.Count == 0)
  53. {
  54. this.RecycleList(set);
  55. this.dictionary.Remove(t);
  56. }
  57. return true;
  58. }
  59. public bool Remove(T t)
  60. {
  61. HashSet<K> set = null;
  62. this.dictionary.TryGetValue(t, out set);
  63. if (set != null)
  64. {
  65. this.RecycleList(set);
  66. }
  67. return this.dictionary.Remove(t);
  68. }
  69. private HashSet<K> FetchList()
  70. {
  71. if (this.queue.Count > 0)
  72. {
  73. HashSet<K> set = this.queue.Dequeue();
  74. set.Clear();
  75. return set;
  76. }
  77. return new HashSet<K>();
  78. }
  79. private void RecycleList(HashSet<K> set)
  80. {
  81. // 防止暴涨
  82. if (this.queue.Count > 100)
  83. {
  84. return;
  85. }
  86. set.Clear();
  87. this.queue.Enqueue(set);
  88. }
  89. public bool Contains(T t, K k)
  90. {
  91. HashSet<K> set;
  92. this.dictionary.TryGetValue(t, out set);
  93. if (set == null)
  94. {
  95. return false;
  96. }
  97. return set.Contains(k);
  98. }
  99. public bool ContainsKey(T t)
  100. {
  101. return this.dictionary.ContainsKey(t);
  102. }
  103. public void Clear()
  104. {
  105. dictionary.Clear();
  106. }
  107. public int Count
  108. {
  109. get
  110. {
  111. int count = 0;
  112. foreach (KeyValuePair<T,HashSet<K>> kv in this.dictionary)
  113. {
  114. count += kv.Value.Count;
  115. }
  116. return count;
  117. }
  118. }
  119. }
  120. }