Files
adas-core/adas-core.Domain/Utils/EquatableDictionary.cs
T

43 lines
1.3 KiB
C#

namespace adas_core.Domain.Utils;
public sealed class EquatableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IEquatable<ComparableDictionary<TKey, TValue>>
where TKey : notnull where TValue : notnull
{
public bool Equals(ComparableDictionary<TKey, TValue>? other)
{
if (other is null) return false;
if (Count != other.Count) return false;
foreach (var pair in this)
{
if (!other.TryGetValue(pair.Key, out var otherValue)) return false;
if (!EqualityComparer<TValue>.Default.Equals(pair.Value, otherValue)) return false;
}
return true;
}
//private readonly Dictionary<TKey, TValue> dictionary = new();
public override bool Equals(object? other)
{
return Equals(other as ComparableDictionary<TKey, TValue>);
}
public override int GetHashCode()
{
var hash = 0;
foreach (var pair in this)
{
var miniHash = 17;
miniHash = miniHash * 31 +
EqualityComparer<TKey>.Default.GetHashCode(pair.Key);
miniHash = miniHash * 31 +
EqualityComparer<TValue>.Default.GetHashCode(pair.Value);
hash ^= miniHash;
}
return hash;
}
// Implementation of IDictionary<,> which just delegates to the dictionary
}