UnOrderMultiMapSet.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * 多重映射结构
  3. *
  4. */
  5. using System.Collections.Generic;
  6. namespace ET
  7. {
  8. public class UnOrderMultiMapSet<T, K>: Dictionary<T, HashSet<K>>
  9. {
  10. // 重用HashSet
  11. public new HashSet<K> this[T t]
  12. {
  13. get
  14. {
  15. HashSet<K> set;
  16. if (!this.TryGetValue(t, out set))
  17. {
  18. set = new HashSet<K>();
  19. }
  20. return set;
  21. }
  22. }
  23. public Dictionary<T, HashSet<K>> GetDictionary()
  24. {
  25. return this;
  26. }
  27. public void Add(T t, K k)
  28. {
  29. HashSet<K> set;
  30. this.TryGetValue(t, out set);
  31. if (set == null)
  32. {
  33. set = new HashSet<K>();
  34. base[t] = set;
  35. }
  36. set.Add(k);
  37. }
  38. public bool Remove(T t, K k)
  39. {
  40. HashSet<K> set;
  41. this.TryGetValue(t, out set);
  42. if (set == null)
  43. {
  44. return false;
  45. }
  46. if (!set.Remove(k))
  47. {
  48. return false;
  49. }
  50. if (set.Count == 0)
  51. {
  52. this.Remove(t);
  53. }
  54. return true;
  55. }
  56. public bool Contains(T t, K k)
  57. {
  58. HashSet<K> set;
  59. this.TryGetValue(t, out set);
  60. if (set == null)
  61. {
  62. return false;
  63. }
  64. return set.Contains(k);
  65. }
  66. public new int Count
  67. {
  68. get
  69. {
  70. int count = 0;
  71. foreach (KeyValuePair<T,HashSet<K>> kv in this)
  72. {
  73. count += kv.Value.Count;
  74. }
  75. return count;
  76. }
  77. }
  78. }
  79. }