Map.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Utilities
  5. {
  6. /// <summary>
  7. /// Based on:
  8. /// http://stackoverflow.com/questions/10966331/two-way-bidirectional-dictionary-in-c
  9. /// </summary>
  10. public class Map<T1, T2>
  11. {
  12. private Dictionary<T1, T2> m_forward = new Dictionary<T1, T2>();
  13. private Dictionary<T2, T1> m_reverse = new Dictionary<T2, T1>();
  14. public Map()
  15. {
  16. m_forward = new Dictionary<T1, T2>();
  17. m_reverse = new Dictionary<T2, T1>();
  18. }
  19. public void Add(T1 key, T2 value)
  20. {
  21. m_forward.Add(key, value);
  22. m_reverse.Add(value, key);
  23. }
  24. public bool ContainsKey(T1 key)
  25. {
  26. return m_forward.ContainsKey(key);
  27. }
  28. public bool ContainsValue(T2 value)
  29. {
  30. return m_reverse.ContainsKey(value);
  31. }
  32. public bool TryGetKey(T2 value, out T1 key)
  33. {
  34. return m_reverse.TryGetValue(value, out key);
  35. }
  36. public bool TryGetValue(T1 key, out T2 value)
  37. {
  38. return m_forward.TryGetValue(key, out value);
  39. }
  40. public void RemoveKey(T1 key)
  41. {
  42. T2 value;
  43. if (m_forward.TryGetValue(key, out value))
  44. {
  45. m_forward.Remove(key);
  46. m_reverse.Remove(value);
  47. }
  48. }
  49. public void RemoveValue(T2 value)
  50. {
  51. T1 key;
  52. if (m_reverse.TryGetValue(value, out key))
  53. {
  54. m_forward.Remove(key);
  55. m_reverse.Remove(value);
  56. }
  57. }
  58. public T2 this[T1 key]
  59. {
  60. get
  61. {
  62. return m_forward[key];
  63. }
  64. }
  65. public T1 GetKey(T2 value)
  66. {
  67. return m_reverse[value];
  68. }
  69. }
  70. }