title: How can I invalidate multiple cache items in C# using string patterns, or otherwise group items to invalidate them together?
body: <p>I often put multiple objects in memory cache that I would like to invalidate collectively. For example, I might cache multiple aspects of record #123, with these cache keys:</p>
  
  <pre><code>record123.foo
  record123.bar
  record123.baz
  </code></pre>
  
  <p>Then, when record #123 changes, I want to invalidate all three keys. But there's no way to string match or search keys. Since there's no "master list" of used cache keys, I can't do this:</p>
  
  <pre><code>cache.Remove(k =&gt; k.StartsWith("record123"))
  </code></pre>
  
  <p>(Sidebar: this would be awesome.)</p>
  
  <p>What I've done in the past is have a <code>CacheManager</code> class, through which I proxy the caching system. I insert objects "through" that class, which keeps the "master list" of all used cache keys in a <code>static List&lt;string&gt;</code> which I <em>can</em> search.</p>
  
  <p>Using that framework, I can do something like this:</p>
  
  <pre><code>public void RemoveByPrefix(string prefix)
  {
     cacheKeys
       .Where(k =&gt; k.StartsWith(prefix))
       .Select(k =&gt; Cache.Remove(k))
   }
  </code></pre>
  
  <p>But I know that I can't be the first person with this problem, and there's got to be a better way to solve it. I suspect it has something to do with <code>CacheDependency</code>, but I have yet to figure it out.</p>
  
  <p>I would like to start doing this properly.</p>