UnOrderMultiMap.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class UnOrderMultiMap<T, K>: Dictionary<T, List<K>>
  6. {
  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. base[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 Array.Empty<K>();
  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. List<K> list;
  61. this.TryGetValue(t, out list);
  62. return list;
  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(K);
  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. }