MultiMap.cs 2.7 KB

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