using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; public class ImmutableDefaultDictionary : IEnumerable> { public readonly TValue defaultValue; public readonly ImmutableDictionary dictionary; public ImmutableDefaultDictionary(TValue defaultValue, ImmutableDictionary dictionary) { this.defaultValue = defaultValue; this.dictionary = dictionary; } public TValue this[TKey key] { get => dictionary.GetOrDefault(key, defaultValue); } public ImmutableDefaultDictionary With(TKey key, TValue value) => new ImmutableDefaultDictionary(defaultValue, dictionary.Add(key, value)); public IEnumerator> GetEnumerator() => dictionary.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator(); } public static class ImmutableDefaultDictionaryExtensionMethods { public static ImmutableDefaultDictionary ToImmutableDefaultDictionary(this IEnumerable e, UValue defaultValue, Func key, Func value) => new ImmutableDefaultDictionary(defaultValue, e.ToImmutableDictionary(key, value)); public static ImmutableDefaultDictionary ToImmutableDefaultDictionary(this ImmutableDictionary d, TValue defaultValue) => new ImmutableDefaultDictionary(defaultValue, d); }