#nullable enable namespace Spark.Core.Collections { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; public static class AggregateDictionary { public static AggregateDictionary Create( IDictionary src1, IDictionary src2, bool isReadOnly = true) where K : notnull => new(src1, src2, isReadOnly); } public class AggregateDictionary : IDictionary where TKey : notnull { readonly IDictionary src1; readonly IDictionary src2; readonly bool isReadOnly; public AggregateDictionary(IDictionary src1, IDictionary src2) { this.src1 = src1; this.src2 = src2; } public AggregateDictionary(IDictionary src1, IDictionary src2, bool isReadOnly = true) { this.src1 = src1; this.src2 = src2; this.isReadOnly = isReadOnly; } public int Count => src1.Count + src2.Count; public bool IsReadOnly => isReadOnly; public ICollection Keys => AggregateCollection.Create(src1.Keys, src2.Keys); public ICollection Values => AggregateCollection.Create(src1.Values, src2.Values); public TValue this[TKey key] { get { if (src1.TryGetValue(key, out var v1)) { return v1; } if (src2.TryGetValue(key, out var v2)) { return v2; } throw new KeyNotFoundException(); } set { if (isReadOnly) { throw new NotSupportedException(); } src1[key] = value; } } public void Add(TKey key, TValue value) => throw new NotSupportedException(); public void Add(KeyValuePair item) => throw new NotSupportedException(); public void Clear() => throw new NotSupportedException(); public bool Contains(KeyValuePair item) => src1.Contains(item) || src2.Contains(item); public bool ContainsKey(TKey key) => (key is TKey k1 && src1.ContainsKey(k1)) || (key is TKey k2 && src2.ContainsKey(k2)); public void CopyTo(KeyValuePair[] array, int arrayIndex) => AggregateCollection.Create(src1, src2).CopyTo(array, arrayIndex); public IEnumerator> GetEnumerator() { foreach (var kv in src1) { yield return new(kv.Key, kv.Value); } foreach (var kv in src2) { yield return new(kv.Key, kv.Value); } } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) => src1.TryGetValue(key, out value) || src2.TryGetValue(key, out value); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); bool IDictionary.Remove(TKey key) => throw new NotSupportedException(); bool ICollection>.Remove(KeyValuePair item) => throw new NotSupportedException(); } }