// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Linq; namespace System.Reactive { internal sealed class Lookup : ILookup { private readonly Dictionary> _dictionary; public Lookup(IEqualityComparer comparer) { _dictionary = new Dictionary>(comparer); } public void Add(K key, E element) { var list = default(List); if (!_dictionary.TryGetValue(key, out list)) { _dictionary[key] = list = new List(); } list.Add(element); } public bool Contains(K key) => _dictionary.ContainsKey(key); public int Count => _dictionary.Count; public IEnumerable this[K key] { get { var list = default(List); if (!_dictionary.TryGetValue(key, out list)) return Enumerable.Empty(); return Hide(list); } } private IEnumerable Hide(List elements) { foreach (var x in elements) { yield return x; } } public IEnumerator> GetEnumerator() { foreach (var kv in _dictionary) { yield return new Grouping(kv); } } private sealed class Grouping : IGrouping { private readonly KeyValuePair> _keyValuePair; public Grouping(KeyValuePair> keyValuePair) { _keyValuePair = keyValuePair; } public K Key => _keyValuePair.Key; public IEnumerator GetEnumerator() => _keyValuePair.Value.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }