MultiMap.cs 2.1 KB

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