BiDictionary.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // Source: https://stackoverflow.com/questions/255341/getting-multiple-keys-of-specified-value-of-a-generic-dictionary#255630
  3. //
  4. using System;
  5. using System.Collections.Generic;
  6. namespace LightReflectiveMirror
  7. {
  8. class BiDictionary<TFirst, TSecond>
  9. {
  10. IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
  11. IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
  12. public void Add(TFirst first, TSecond second)
  13. {
  14. if (firstToSecond.ContainsKey(first) ||
  15. secondToFirst.ContainsKey(second))
  16. {
  17. throw new ArgumentException("Duplicate first or second");
  18. }
  19. firstToSecond.Add(first, second);
  20. secondToFirst.Add(second, first);
  21. }
  22. public bool TryGetByFirst(TFirst first, out TSecond second)
  23. {
  24. return firstToSecond.TryGetValue(first, out second);
  25. }
  26. public void Remove(TFirst first)
  27. {
  28. secondToFirst.Remove(firstToSecond[first]);
  29. firstToSecond.Remove(first);
  30. }
  31. public ICollection<TFirst> GetAllKeys()
  32. {
  33. return secondToFirst.Values;
  34. }
  35. public bool TryGetBySecond(TSecond second, out TFirst first)
  36. {
  37. return secondToFirst.TryGetValue(second, out first);
  38. }
  39. public TSecond GetByFirst(TFirst first)
  40. {
  41. return firstToSecond[first];
  42. }
  43. public TFirst GetBySecond(TSecond second)
  44. {
  45. return secondToFirst[second];
  46. }
  47. }
  48. }