MultiMap.cs 1.8 KB

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