Lookup.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace System.Reactive
  6. {
  7. class Lookup<K, E> : ILookup<K, E>
  8. {
  9. Dictionary<K, List<E>> d;
  10. public Lookup(IEqualityComparer<K> comparer)
  11. {
  12. d = new Dictionary<K, List<E>>(comparer);
  13. }
  14. public void Add(K key, E element)
  15. {
  16. var list = default(List<E>);
  17. if (!d.TryGetValue(key, out list))
  18. d[key] = list = new List<E>();
  19. list.Add(element);
  20. }
  21. public bool Contains(K key)
  22. {
  23. return d.ContainsKey(key);
  24. }
  25. public int Count
  26. {
  27. get { return d.Count; }
  28. }
  29. public IEnumerable<E> this[K key]
  30. {
  31. get { return Hide(d[key]); }
  32. }
  33. private IEnumerable<E> Hide(List<E> elements)
  34. {
  35. foreach (var x in elements)
  36. yield return x;
  37. }
  38. public IEnumerator<IGrouping<K, E>> GetEnumerator()
  39. {
  40. foreach (var kv in d)
  41. yield return new Grouping(kv);
  42. }
  43. class Grouping : IGrouping<K, E>
  44. {
  45. KeyValuePair<K, List<E>> kv;
  46. public Grouping(KeyValuePair<K, List<E>> kv)
  47. {
  48. this.kv = kv;
  49. }
  50. public K Key
  51. {
  52. get { return kv.Key; }
  53. }
  54. public IEnumerator<E> GetEnumerator()
  55. {
  56. return kv.Value.GetEnumerator();
  57. }
  58. Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
  59. {
  60. return GetEnumerator();
  61. }
  62. }
  63. Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
  64. {
  65. return GetEnumerator();
  66. }
  67. }
  68. }