UnOrderMultiMapSet.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * 多重映射结构
  3. *
  4. */
  5. using System.Collections.Generic;
  6. namespace Fort23.Core
  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. }