Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query On IDictionaryEnumerator Possible?

I need to clear items from cache that contain a specific string in the key. I have started with the following and thought I might be able to do a linq query

var enumerator = HttpContext.Current.Cache.GetEnumerator();

But I can't? I was hoping to do something like

var enumerator = HttpContext.Current.Cache.GetEnumerator().Key.Contains("subcat");

Any ideas on how I could achieve this?

like image 212
YodasMyDad Avatar asked Dec 04 '22 09:12

YodasMyDad


1 Answers

The Enumerator created by the Cache generates DictionaryEntry objects. Furthermore, a Cache may have only string keys.

Thus, you can write the following:

var httpCache = HttpContext.Current.Cache;
var toRemove = httpCache.Cast<DictionaryEntry>()
    .Select(de=>(string)de.Key)
    .Where(key=>key.Contains("subcat"))
    .ToArray(); //use .ToArray() to avoid concurrent modification issues.

foreach(var keyToRemove in toRemove)
    httpCache.Remove(keyToRemove);

However, this is a potentially slow operation when the cache is large: the cache is not designed to be used like this. You should ask yourself whether an alternative design isn't possible and preferable. Why do you need to remove several cache keys at once, and why aren't you grouping cache keys by substring?

like image 162
Eamon Nerbonne Avatar answered Dec 21 '22 00:12

Eamon Nerbonne