title: ASP.NET Caching, limiting the number of entries in cache
body: <p>I'm trying to implement data caching for a web app in ASP.NET, this is for class and I've been asked to limit the number of entries in the ObjectCache, not by memory size but by the number of entries itself. This is quite easy since I can call ObjectCache.Count, but when the cache grows beyond the established limit (5, just for testing) I can't figure out how to remove the oldest element stored since it's alphabetically sorted.</p>
  
  <p>This is being implemented in a Service, at the Data Access layer so I can't use any additional structure like a Queue to keep track of the insertions in the cache.</p>
  
  <p>What can I do? Is there a way to filter or get the older element in the cache?</p>
  
  <p>Here's the method code</p>
  
  <pre><code>        public List&lt;EventSummary&gt; FindEvents(String keywords, long categoryId, int start, int count)
      {
          string queryKey = "FindEvent-" + start + ":" + count + "-" + keywords.Trim() + "-" + categoryId;
          ObjectCache cache = MemoryCache.Default;
          List&lt;EventSummary&gt; val = (List&lt;EventSummary&gt;)cache.Get(queryKey);
          if (val != null)
              return val;
  
          Category evnCategory = CategoryDao.Find(categoryId);
          List&lt;Event&gt; fullResult = EventDao.FindByEventCategoryAndKeyword(evnCategory, keywords, start, count);
          List&lt;EventSummary&gt; summaryResult = new List&lt;EventSummary&gt;();
  
          foreach (Event evento in fullResult)
          {
              summaryResult.Add(new EventSummary(evento.evnId, evento.evnName, evento.Category, evento.evnDate));
          }
  
          if (cache.Count() &gt;= maxCacheSize)
          {
              //WHAT SHOULD I DO HERE?
          }
  
          cache.Add(queryKey, summaryResult, DateTime.Now.AddDays(cacheDays));
  
          return summaryResult;
      }
  </code></pre>