MultiMap.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace Common.Base
  4. {
  5. public class MultiMap<T, K>
  6. {
  7. private readonly SortedDictionary<T, List<K>> dictionary = 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 KeyValuePair<T, List<K>> First
  27. {
  28. get
  29. {
  30. return dictionary.First();
  31. }
  32. }
  33. public bool Remove(T t, K k)
  34. {
  35. List<K> list;
  36. this.dictionary.TryGetValue(t, out list);
  37. if (list == null)
  38. {
  39. return false;
  40. }
  41. if (!list.Remove(k))
  42. {
  43. return false;
  44. }
  45. if (list.Count == 0)
  46. {
  47. this.dictionary.Remove(t);
  48. }
  49. return true;
  50. }
  51. public bool Remove(T t)
  52. {
  53. return this.dictionary.Remove(t);
  54. }
  55. /// <summary>
  56. /// 不返回内部的list,copy一份出来
  57. /// </summary>
  58. /// <param name="t"></param>
  59. /// <returns></returns>
  60. public K[] GetAll(T t)
  61. {
  62. List<K> list;
  63. this.dictionary.TryGetValue(t, out list);
  64. if (list == null)
  65. {
  66. return new K[0];
  67. }
  68. var newList = new List<K>();
  69. foreach (K k in list)
  70. {
  71. newList.Add(k);
  72. }
  73. return newList.ToArray();
  74. }
  75. /// <summary>
  76. /// 返回内部的list
  77. /// </summary>
  78. /// <param name="t"></param>
  79. /// <returns></returns>
  80. public List<K> this[T t]
  81. {
  82. get
  83. {
  84. List<K> list;
  85. this.dictionary.TryGetValue(t, out list);
  86. return list;
  87. }
  88. }
  89. public K GetOne(T t)
  90. {
  91. List<K> list;
  92. this.dictionary.TryGetValue(t, out list);
  93. if ((list != null) && (list.Count > 0))
  94. {
  95. return list[0];
  96. }
  97. return default(K);
  98. }
  99. public bool Contains(T t, K k)
  100. {
  101. List<K> list;
  102. this.dictionary.TryGetValue(t, out list);
  103. if (list == null)
  104. {
  105. return false;
  106. }
  107. return list.Contains(k);
  108. }
  109. }
  110. }