我需要从缓存中清除键中包含特定字符串的项目。我从以下内容开始,并认为我可以进行 linq 查询
var enumerator = HttpContext.Current.Cache.GetEnumerator();
但是我不能?我希望做类似的事情
var enumerator = HttpContext.Current.Cache.GetEnumerator().Key.Contains("subcat");
关于如何实现这一点有什么想法吗?
最佳答案
由 Cache
创建的 Enumerator 生成 DictionaryEntry
对象。此外,Cache
可能只有 string
键。
因此,你可以这样写:
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);
但是,当缓存很大时,这可能是一个很慢的操作:缓存不是为这样使用而设计的。您应该问问自己,替代设计是否可行且更可取。为什么需要一次删除多个缓存键,为什么不按子字符串对缓存键进行分组?
关于c# - IDictionaryEnumerator 上的 Linq 查询可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862120/