MultiMap.cs 2.1 KB

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