2011-02-01 37 views
4

我需要清除缓存中包含密钥中特定字符串的项目。我已经开始与以下,并认为我可能能够做一个linq查询Linq Query IDictionaryEnumerator可能吗?

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

但我不能?我希望能做些类似于

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

有关我如何实现这一点的任何想法?

+5

撇开:枚举整个缓存本来就是一个在繁忙的网站上的一个坏主意...... – 2011-02-01 11:54:22

+0

是的,我听到你们所有......回到绘图板 – leen3o 2011-02-01 12:33:36

回答

10

Cache创建的枚举器生成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); 

然而,这是一个潜在的慢操作时,缓存大:在缓存中没有这样设计的使用。你应该问自己,一种替代设计是不可能的,更可取的。为什么你需要一次删除多个缓存键,为什么不通过子串分组缓存键?

2

我不认为这是遍历整个缓存反正一个伟大的想法,但你可以用类似做非LINQ:

var iter = HttpContext.Current.Cache.GetEnumerator(); 
    using (iter as IDisposable) 
    { 
     while (iter.MoveNext()) 
     { 
      string s; 
      if ((s = iter.Key as string) != null && s.Contains("subcat")) 
      { 
       //... let the magic happen 
      } 
     } 
    } 

与LINQ做到这一点,你可以做是这样的:

public static class Utils 
{ 
    public static IEnumerable<KeyValuePair<object, object>> ForLinq(this IDictionaryEnumerator iter) 
    { 
     using (iter as IDisposable) 
     { 
      while (iter.MoveNext()) yield return new KeyValuePair<object, object>(iter.Key, iter.Value); 
     } 
    } 
} 

和使用,如:

var items = HttpContext.Current.Cache.GetEnumerator().ForLinq() 
     .Where(pair => ((string)pair.Key).Contains("subcat")); 
+0

感谢上述,赞赏 - 但你会怎么去清除缓存的项目,以某个键开始...? – leen3o 2011-02-01 12:09:11

+1

通过设计,使我不必...对不起,不是一个很好的答案恐怕 – 2011-02-01 12:19:52

5

由于Cache是​​一个IEnumerable,你可以自由地将所有需要的LINQ方法应用到它。你唯一需要的是将其转换为IEnumerable的<的DictionaryEntry >:

 

var keysQuery = HttpContext.Current.Cache 
    .Cast<DictionaryEntry>() 
    .Select(entry => (string)entry.Key) 
    .Where(key => key.Contains("subcat")); 
 

现在keysQuery是“SUBCAT”开始的所有键的非严格的集合。但是如果你需要从缓存中删除这样的条目,最简单的方法就是使用foreach语句。