MultiMapSet.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace ET
  5. {
  6. public class MultiMapSet<T, K>: SortedDictionary<T, HashSet<K>>
  7. {
  8. private readonly HashSet<K> Empty = new HashSet<K>();
  9. public void Add(T t, K k)
  10. {
  11. HashSet<K> list;
  12. this.TryGetValue(t, out list);
  13. if (list == null)
  14. {
  15. list = new HashSet<K>();
  16. this.Add(t, list);
  17. }
  18. list.Add(k);
  19. }
  20. public bool Remove(T t, K k)
  21. {
  22. HashSet<K> list;
  23. this.TryGetValue(t, out list);
  24. if (list == null)
  25. {
  26. return false;
  27. }
  28. if (!list.Remove(k))
  29. {
  30. return false;
  31. }
  32. if (list.Count == 0)
  33. {
  34. this.Remove(t);
  35. }
  36. return true;
  37. }
  38. /// <summary>
  39. /// 不返回内部的list,copy一份出来
  40. /// </summary>
  41. /// <param name="t"></param>
  42. /// <returns></returns>
  43. public K[] GetAll(T t)
  44. {
  45. HashSet<K> list;
  46. this.TryGetValue(t, out list);
  47. if (list == null)
  48. {
  49. return Array.Empty<K>();
  50. }
  51. return list.ToArray();
  52. }
  53. /// <summary>
  54. /// 返回内部的list
  55. /// </summary>
  56. /// <param name="t"></param>
  57. /// <returns></returns>
  58. public new HashSet<K> this[T t]
  59. {
  60. get
  61. {
  62. this.TryGetValue(t, out var list);
  63. return list ?? Empty;
  64. }
  65. }
  66. public K GetOne(T t)
  67. {
  68. HashSet<K> list;
  69. this.TryGetValue(t, out list);
  70. if (list != null && list.Count > 0)
  71. {
  72. return list.FirstOrDefault();
  73. }
  74. return default;
  75. }
  76. public bool Contains(T t, K k)
  77. {
  78. HashSet<K> list;
  79. this.TryGetValue(t, out list);
  80. if (list == null)
  81. {
  82. return false;
  83. }
  84. return list.Contains(k);
  85. }
  86. }
  87. }