Created
March 2, 2022 07:46
-
-
Save qluana7/b9dfae8b24537a383ae576ae385e44c7 to your computer and use it in GitHub Desktop.
Key 값의 갯수를 포함하는 간단한 Dictionary입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CountDictionary<TKey> : IDictionary<TKey, int> where TKey : notnull | |
{ | |
public CountDictionary() | |
{ | |
Collections = new(); | |
} | |
public CountDictionary(IEnumerable<KeyValuePair<TKey, int>> pair) | |
{ | |
Collections = new(pair); | |
} | |
private Dictionary<TKey, int> Collections { get; init; } | |
public int this[TKey key] { get => Collections[key]; set => Collections[key] = value; } | |
public ICollection<TKey> Keys => Collections.Keys; | |
public ICollection<int> Values => Collections.Values; | |
public int Count => Keys.Count; | |
public bool IsReadOnly => false; | |
public void Add(TKey key, int value) | |
{ | |
if (Collections.ContainsKey(key)) | |
Collections[key] += value; | |
else | |
Collections.Add(key, value); | |
} | |
public void Add(TKey key) | |
=> Add(key, 1); | |
public void Sub(TKey key, int value) | |
{ | |
if (Collections.ContainsKey(key)) | |
Collections[key] -= value; | |
else | |
throw new KeyNotFoundException(); | |
} | |
public void Sub(TKey key) | |
=> Sub(key, 1); | |
public void Add(KeyValuePair<TKey, int> item) | |
=> Add(item.Key, item.Value); | |
public void Clear() | |
=> Collections.Clear(); | |
public bool Contains(KeyValuePair<TKey, int> item) | |
=> Collections.Contains(item); | |
public bool ContainsKey(TKey key) | |
=> Collections.ContainsKey(key); | |
public void CopyTo(KeyValuePair<TKey, int>[] array, int arrayIndex) | |
=> new NotImplementedException(); | |
public IEnumerator<KeyValuePair<TKey, int>> GetEnumerator() | |
=> Collections.GetEnumerator(); | |
public bool Remove(TKey key) | |
=> Collections.Remove(key); | |
public bool Remove(KeyValuePair<TKey, int> item) | |
=> Collections.Remove(item.Key); | |
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out int value) | |
{ | |
if (Collections.TryGetValue(key, out int values)) | |
{ | |
value = values; | |
return true; | |
} | |
value = default; | |
return false; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
=> Collections.GetEnumerator(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment