using System.Text;
namespace StabilityMatrix.Core.Extensions;
public static class DictionaryExtensions
{
///
/// Adds all items from another dictionary to this dictionary.
///
public static void Update(
this IDictionary source,
IReadOnlyDictionary collection
)
where TKey : notnull
{
foreach (var item in collection)
{
source[item.Key] = item.Value;
}
}
///
/// Formats a dictionary as a string for debug/logging purposes.
///
public static string ToRepr(
this IDictionary source
)
where TKey : notnull
{
var sb = new StringBuilder();
sb.Append('{');
foreach (var (key, value) in source)
{
// for string types, use ToRepr
if (key is string keyString)
{
sb.Append($"{keyString.ToRepr()}=");
}
else
{
sb.Append($"{key}=");
}
if (value is string valueString)
{
sb.Append($"{valueString.ToRepr()}, ");
}
else
{
sb.Append($"{value}, ");
}
}
sb.Append('}');
return sb.ToString();
}
///
/// Get or add a value to a dictionary.
///
public static TValue GetOrAdd(this IDictionary dict, TKey key)
where TValue : new()
{
if (!dict.TryGetValue(key, out var val))
{
val = new TValue();
dict.Add(key, val);
}
return val;
}
}