using System.Collections; using System.Collections.Immutable; using Connected.Interop; namespace Connected.Collections.Iterators; internal class DictionaryIterator : IIterator { private readonly object _value; private IDictionary _result; public DictionaryIterator(object value) { _value = value; if (value is not IDictionary dictionary) return; Enumerator = dictionary.GetEnumerator(); CreateResult(); } public static bool CanHandle(object value) { var arguments = value.GetType().GetGenericArguments(); var kvp = typeof(KeyValuePair<,>).MakeGenericType(arguments); var en = typeof(IEnumerable<>).MakeGenericType(kvp); return value.GetType() == en; } private void CreateResult() { if (_value.GetType() == typeof(IImmutableDictionary<,>)) _result = _value.GetType().MakeGenericType(_value.GetType().GenericTypeArguments).CreateInstance(); } private IDictionaryEnumerator? Enumerator { get; } public object? Current => Enumerator?.Value; public object? Result { get { if (_value is null) return null; throw new NotImplementedException(); } } public bool MoveNext() { if (Enumerator is null) return false; return Enumerator.MoveNext(); } public void Reset() { if (Enumerator is null) return; Enumerator.Reset(); } public void Add(object value) { if (Current is null || Enumerator is null) throw new InvalidOperationException(SR.ErrIteratorCurrentNull); _result.Add(Enumerator.Key, value); } }