using System.Collections.Immutable;
namespace Sandbox;
///
/// Extension methods for working with immutable dictionaries.
/// Provides functional-style operations for creating modified copies.
///
internal static class DictionaryExtensions
{
///
/// Returns a new dictionary with the specified key-value pair added or updated.
/// If the value already exists and is equal, returns the original dictionary.
///
public static IReadOnlyDictionary With( this IReadOnlyDictionary dict, TKey key, TValue value )
where TKey : IEquatable
{
if ( dict.TryGetValue( key, out var existing ) && Equals( existing, value ) )
{
return dict;
}
var builder = ImmutableDictionary.CreateBuilder();
builder.AddRange( dict );
builder[key] = value;
return builder.ToImmutable();
}
///
/// Returns a new dictionary with the specified key removed.
/// If the key doesn't exist, returns the original dictionary.
///
public static IReadOnlyDictionary Without( this IReadOnlyDictionary dict, TKey key )
where TKey : IEquatable
{
if ( !dict.ContainsKey( key ) )
{
return dict;
}
var builder = ImmutableDictionary.CreateBuilder();
builder.AddRange( dict.Where( x => !x.Key.Equals( key ) ) );
return builder.ToImmutable();
}
}