Lookup.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. namespace System.Reactive
  8. {
  9. class Lookup<K, E> : ILookup<K, E>
  10. {
  11. private readonly Dictionary<K, List<E>> d;
  12. public Lookup(IEqualityComparer<K> comparer)
  13. {
  14. d = new Dictionary<K, List<E>>(comparer);
  15. }
  16. public void Add(K key, E element)
  17. {
  18. var list = default(List<E>);
  19. if (!d.TryGetValue(key, out list))
  20. d[key] = list = new List<E>();
  21. list.Add(element);
  22. }
  23. public bool Contains(K key)
  24. {
  25. return d.ContainsKey(key);
  26. }
  27. public int Count
  28. {
  29. get { return d.Count; }
  30. }
  31. public IEnumerable<E> this[K key]
  32. {
  33. get
  34. {
  35. var list = default(List<E>);
  36. if (!d.TryGetValue(key, out list))
  37. return Enumerable.Empty<E>();
  38. return Hide(list);
  39. }
  40. }
  41. private IEnumerable<E> Hide(List<E> elements)
  42. {
  43. foreach (var x in elements)
  44. yield return x;
  45. }
  46. public IEnumerator<IGrouping<K, E>> GetEnumerator()
  47. {
  48. foreach (var kv in d)
  49. yield return new Grouping(kv);
  50. }
  51. class Grouping : IGrouping<K, E>
  52. {
  53. KeyValuePair<K, List<E>> kv;
  54. public Grouping(KeyValuePair<K, List<E>> kv)
  55. {
  56. this.kv = kv;
  57. }
  58. public K Key
  59. {
  60. get { return kv.Key; }
  61. }
  62. public IEnumerator<E> GetEnumerator()
  63. {
  64. return kv.Value.GetEnumerator();
  65. }
  66. IEnumerator IEnumerable.GetEnumerator()
  67. {
  68. return GetEnumerator();
  69. }
  70. }
  71. IEnumerator IEnumerable.GetEnumerator()
  72. {
  73. return GetEnumerator();
  74. }
  75. }
  76. }