I have an on-demand cache implemented using HttpContext.Current.Items like this:
private static readonly Lazy<CacheCurrentCall> lazy = new Lazy<CacheCurrentCall>(() => new CacheCurrentCall()); public static CacheCurrentCall Instance { get { IDictionary items = HttpContext.Current.Items; if (!items.Contains("CacheCurrentCall")) { items["CacheCurrentCall"] = new CacheCurrentCall(); } return items["CacheCurrentCall"] as CacheCurrentCall; } } private CacheCurrentCall() { } public void Add<T>(T o, string key, int cacheDurationSeconds = 0) { HttpContext.Current.Items.Add(key, o); } public void Clear(string key) { HttpContext.Current.Items.Remove(key); } public bool Exists(string key) { return HttpContext.Current.Items[key] != null; } public bool Get<T>(string key, out T value) { try { if (!Exists(key)) { value = default(T); return false; } value = (T)HttpContext.Current.Items[key]; } catch { value = default(T); return false; } return true; }
Now I will need to delete all the keys, starting from a specific line, and so I was thinking of a method like this
public IEnumerable<string> GetKey (Func<string, bool> condition)
and then scroll through the results and clear them (I could even clearly define the explicit abstraction of the lambda expression, I think). But I was lost trying to implement such a method, if it is actually possible.
Any help?
thanks
Edit:
Service, I tried (I blindly tried some things, but more or less followed this path)
public IEnumerable<string> GetKeys(Func<string, bool> condition) { List<string> list = new List<string>(); foreach (var key in HttpContext.Current.Items.Keys) { if (condition(key as string)) { list.Add(key as string); } } return list; }
But I get:
Object reference not set to object instance
Now I will try pswg, which, moreover, it probably works much more elegantly for my eyes.
Second edit:
I needed to change the solution pswg a bit. I do not store lines in the cache, but other types of objects, so I use it now
public IEnumerable<string> GetKeys (Func<string, bool> condition) { return HttpContext.Current.Items .Cast<DictionaryEntry>() .Where(e => e.Key is string && condition(e.Key as string)) .Select(e => e.Key as string); }
And the call to clear the cache, for example, is
public void ClearCache() { var ownedItemSummaryKeys = CacheCurrentCall.Instance.GetKeys(k => k.Contains("OwnedItemSummaryCurrent")); foreach (var ownedItemSummaryKey in ownedItemSummaryKeys.ToList()) { CacheCurrentCall.Instance.Clear(ownedItemSummaryKey); } }