using System.Collections.Generic; using JD.Kernel.StaticHelpers; namespace JD.Collections { /// /// Counts the occurrences of key. /// public class OccurencesCounter { #region Variables private readonly Dictionary m_counts = new Dictionary(); #endregion #region Properties public ICollection Keys { get { return m_counts.Keys; } } /// /// Enumerates all the items (in key) and the count of occurrences (the value). /// public ICollection> Occurences { get { return m_counts; } } public bool IsEmpty { get { return m_counts.Count == 0; } } #endregion #region Methods public int OccurenceOf(TKey key) { Throw.IfNull(key, "key"); int count; m_counts.TryGetValue(key, out count); return count; } /// /// Increments the occurence for the given . Returns 1 if it's the first time the key is referenced. /// /// /// public int Increment(TKey key) { Throw.IfNull(key, "key"); return Increment(key, 1); } /// /// Increments the occurence for the given . /// public int Increment(TKey key, int increment) { Throw.IfNull(key, "key"); int count; if (!m_counts.TryGetValue(key, out count)) { count = 0; } count += increment; SetValue(key, count); return count; } /// /// Decrements the occurence for the given . Returns 0 if it's the last time the key is referenced. /// /// /// public int Decrement(TKey key) { Throw.IfNull(key, "key"); int count; if (!m_counts.TryGetValue(key, out count)) { count = 0; } count--; SetValue(key, count); return count; } /// /// Whether a key in the given collection has occurred at least one time. /// /// /// public bool OccurenceOfAny(params TKey[] keys) { Throw.IfNull(keys, "keys"); foreach (TKey currentKey in keys) { if (OccurenceOf(currentKey) > 0) { return true; } } return false; } /// /// Clear. /// public void Clear() { m_counts.Clear(); } /// /// Sets the occurence count directly. /// public void SetValue(TKey key, int count) { if (count == 0) { m_counts.Remove(key); } else { m_counts[key] = count; } } #endregion } }