UnOrderMultiMap.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Fort23.Core
  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. }