Skip to content

Instantly share code, notes, and snippets.

@theodorzoulias
theodorzoulias / JsonKeyedCollectionBase.cs
Last active April 19, 2024 12:24
JsonKeyedCollectionBase for JSON serialization/deserialization
// Related: https://github.com/dotnet/runtime/issues/101003 -- [API Proposal]: New method HashSet<T>.Add that replaces an existing element if found
abstract class JsonKeyedCollectionBase<TKey, TItem> : ICollection<TItem>, IEqualityComparer<TItem>
{
private readonly HashSet<TItem> _set;
protected abstract TKey GetKeyForItem(TItem item);
protected abstract TItem GetItemForKey(TKey key);
protected virtual IEqualityComparer<TKey> KeyComparer => EqualityComparer<TKey>.Default;
protected virtual IComparer<TItem> EnumerationComparer => null;