Lookup.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. internal sealed class Lookup<K, E> : ILookup<K, E>
  10. {
  11. private readonly Dictionary<K, List<E>> _dictionary;
  12. public Lookup(IEqualityComparer<K> comparer)
  13. {
  14. _dictionary = new Dictionary<K, List<E>>(comparer);
  15. }
  16. public void Add(K key, E element)
  17. {
  18. var list = default(List<E>);
  19. if (!_dictionary.TryGetValue(key, out list))
  20. {
  21. _dictionary[key] = list = new List<E>();
  22. }
  23. list.Add(element);
  24. }
  25. public bool Contains(K key) => _dictionary.ContainsKey(key);
  26. public int Count => _dictionary.Count;
  27. public IEnumerable<E> this[K key]
  28. {
  29. get
  30. {
  31. var list = default(List<E>);
  32. if (!_dictionary.TryGetValue(key, out list))
  33. return Enumerable.Empty<E>();
  34. return Hide(list);
  35. }
  36. }
  37. private IEnumerable<E> Hide(List<E> elements)
  38. {
  39. foreach (var x in elements)
  40. {
  41. yield return x;
  42. }
  43. }
  44. public IEnumerator<IGrouping<K, E>> GetEnumerator()
  45. {
  46. foreach (var kv in _dictionary)
  47. {
  48. yield return new Grouping(kv);
  49. }
  50. }
  51. private sealed class Grouping : IGrouping<K, E>
  52. {
  53. private readonly KeyValuePair<K, List<E>> _keyValuePair;
  54. public Grouping(KeyValuePair<K, List<E>> keyValuePair)
  55. {
  56. _keyValuePair = keyValuePair;
  57. }
  58. public K Key => _keyValuePair.Key;
  59. public IEnumerator<E> GetEnumerator() => _keyValuePair.Value.GetEnumerator();
  60. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  61. }
  62. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  63. }
  64. }