Skip to content

Commit 65895c7

Browse files
committed
Cache equality comparer ctor
1 parent 06f4b68 commit 65895c7

File tree

1 file changed

+3
-36
lines changed

1 file changed

+3
-36
lines changed

Noggog.CSharpExt/Containers/Cache.cs

Lines changed: 3 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class Cache<TObject, TKey> : ICache<TObject, TKey>
99
public static readonly IReadOnlyCache<TObject, TKey> Empty = new Cache<TObject, TKey>(_ => default!);
1010

1111
private readonly Func<TObject, TKey> _keySelector;
12-
private Dictionary<TKey, TObject> _dict = new();
12+
private readonly Dictionary<TKey, TObject> _dict;
1313

1414
public TObject this[TKey key] => _dict[key];
1515

@@ -21,8 +21,9 @@ public class Cache<TObject, TKey> : ICache<TObject, TKey>
2121

2222
public IEnumerable<KeyValuePair<TKey, TObject>> KeyValues => _dict;
2323

24-
public Cache(Func<TObject, TKey> keySelector)
24+
public Cache(Func<TObject, TKey> keySelector, IEqualityComparer<TKey>? equalityComparer = null)
2525
{
26+
_dict = new Dictionary<TKey, TObject>(equalityComparer);
2627
_keySelector = keySelector ?? throw new ArgumentNullException(nameof(keySelector));
2728
}
2829

@@ -51,40 +52,6 @@ public void Remove(IEnumerable<TKey> keys)
5152

5253
return default;
5354
}
54-
55-
public void Refresh()
56-
{
57-
var tmp = _dict;
58-
_dict = new Dictionary<TKey, TObject>();
59-
foreach (var item in tmp.Values)
60-
{
61-
_dict[_keySelector(item)] = item;
62-
}
63-
}
64-
65-
public void Refresh(IEnumerable<TKey> keys)
66-
{
67-
List<TObject> objs = new();
68-
foreach (var key in keys)
69-
{
70-
if (_dict.TryGetValue(key, out var val))
71-
{
72-
objs.Add(val);
73-
_dict.Remove(key);
74-
}
75-
}
76-
foreach (var obj in objs)
77-
{
78-
_dict[_keySelector(obj)] = obj;
79-
}
80-
}
81-
82-
public void Refresh(TKey key)
83-
{
84-
if (!TryGetValue(key, out var val)) return;
85-
_dict.Remove(key);
86-
_dict[_keySelector(val)] = val;
87-
}
8855

8956
public IEnumerator<IKeyValue<TKey, TObject>> GetEnumerator()
9057
{

0 commit comments

Comments
 (0)