C# Sorted List by Value with Object

前端 未结 9 1031
失恋的感觉
失恋的感觉 2021-01-21 20:06

I\'m trying to create an \"ordered\" cache of objects in C#, where the order is determined by how many times that has been accessed.

I\'ve looked into Dictionary, Sorted

9条回答
  •  庸人自扰
    2021-01-21 20:15

    The Cache below exposes a simple Add/Get interface for adding and retrieving items from the cache, which could obviously be improved upon. It implements IEnumerable, which enumerates through the cache with the required behaviour. There are obviously threading issues here that would need to be addressed.

    public class Cache: IEnumerable
    {
        //Dictionary to hold the values of the cache
        private Dictionary m_cacheStore = new Dictionary();
    
        //Dictionary to hold the number of times each key has been accessed
        private Dictionary m_cacheAccessCount = new Dictionary(); 
    
        public T Get(string cacheKey)
        {
            if (m_cacheStore.ContainsKey(cacheKey))
            {
                //Increment access counter
                if (!m_cacheAccessCount.ContainsKey(cacheKey))
                    m_cacheAccessCount.Add(cacheKey, 0);
                m_cacheAccessCount[cacheKey] = m_cacheAccessCount[cacheKey] + 1;
    
                return m_cacheStore[cacheKey];
            }
            throw new KeyNotFoundException(cacheKey);
        }
    
        public int GetHits(string cacheKey)
        {
            return m_cacheAccessCount.ContainsKey(cacheKey) ? m_cacheAccessCount[cacheKey] : 0;
        }
    
        public void Add(string cacheKey, T cacheValue)
        {
            if(m_cacheStore.ContainsKey(cacheKey))
                throw new ArgumentException(string.Format("An element with the key {0} already exists in the cache", cacheKey));
            m_cacheStore.Add(cacheKey, cacheValue);
        }
    
        #region Implementation of IEnumerable
    
        public IEnumerator GetEnumerator()
        {
            foreach (var source in m_cacheAccessCount.OrderBy(kvp => kvp.Value))
            {
                yield return m_cacheStore[source.Key];
            }
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    
        #endregion
    }
    

提交回复
热议问题