MultiMap.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System.Collections.Generic;
  2. namespace Base
  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. var newList = new List<K>();
  61. foreach (K k in list)
  62. {
  63. newList.Add(k);
  64. }
  65. return newList.ToArray();
  66. }
  67. /// <summary>
  68. /// 返回内部的list
  69. /// </summary>
  70. /// <param name="t"></param>
  71. /// <returns></returns>
  72. public List<K> this[T t]
  73. {
  74. get
  75. {
  76. List<K> list;
  77. this.dictionary.TryGetValue(t, out list);
  78. return list;
  79. }
  80. }
  81. public K GetOne(T t)
  82. {
  83. List<K> list;
  84. this.dictionary.TryGetValue(t, out list);
  85. if ((list != null) && (list.Count > 0))
  86. {
  87. return list[0];
  88. }
  89. return default(K);
  90. }
  91. public bool Contains(T t, K k)
  92. {
  93. List<K> list;
  94. this.dictionary.TryGetValue(t, out list);
  95. if (list == null)
  96. {
  97. return false;
  98. }
  99. return list.Contains(k);
  100. }
  101. }
  102. }