Use wildcards when searching in HttpContext.Cache

1.7k Views Asked by At

Is there a way to use wildcards or a regex to search and remove items from HttpContext.Cache?

I can have in my cache "item_1", "item_2",...,"item_n" and I want to remove from cache all values that are related to keys with the pattern "item_*". How to achieve that without checking if the item exists and then remove it?

Ex:

instead of:

HttpContext.Current.Cache.Remove("item_1")
HttpContext.Current.Cache.Remove("item_2")
HttpContext.Current.Cache.Remove("item_3")

I want something like:

HttpContext.Current.Cache.Remove("item_*")
2

There are 2 best solutions below

0
scheien On BEST ANSWER

You could loop the items like this:

foreach(var key in HttpContext.Current.Cache)
{
    if (key.StartsWith("item_"))
    {
        // remove the corresponding item here.
    }
}

The basic sample, and needs some tweaking to match your implementation.

AFAIK you can't remove items based on wildcards, as you need the specific key. (Please prove me wrong)

0
vks On
^HttpContext\.Current\.Cache\.Remove\("item_.*?"\)$

You can try this.Replace with empty string.See demo.

http://regex101.com/r/sU3fA2/65