views:

71

answers:

2

Does ASP.NET support the notion of multiple caches with the built-in caching? My end goal is to be able to pull out all items of a certain type from the cache. This could be done with a separate cache per type, or through some sort of naming convention. Ideally, I'd be able to use LINQ in the following manner:

var items = (from item in cache.Items where item.Key.StartsWith("person") select item);

Or perhaps I could define a separate "person" cache. Is this possible with the built-in system or will I need to use a third party alternative?

Thanks

+3  A: 

In fact, Cache class already implements IEnumerable, so you can foreach over it (and query it with LINQ, for that matter). Documentation does not state what is the type of an object this enumerator yields, but this can be found out in debugger once and forever.

Anton Gogolev
I realized it supported IEnumerable, but I thought it was simply returning untyped objects of the values. Actually, it returns an enumeration of DictionaryEntry objects, which have both the key and value.So I can now do:var people = (from entry in cache where entry.Key.StartsWith("person") select entry.Value);
Brian Vallelunga
+1  A: 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Cache.Insert("nord", new Person("Nord"));
        Cache.Insert("bert", new Person("Bert"));
        Cache.Insert("frog", new Animal("Kermit"));

        foreach (Person p in Cache.CacheOfType<Person>())
        {
            Response.Write(p.Name); //prints NordBert
        }
        Response.Write("<br>");
        foreach (Animal a in Cache.CacheOfType<Animal>())
        {
            Response.Write(a.Name); //prints Kermit
        }
    }
}

public static class CacheExt
{
    public static IEnumerable<T> CacheOfType<T>(this System.Web.Caching.Cache cache) where T : class
    {
        foreach (System.Collections.DictionaryEntry i in cache)
        {
            if (i.Value as T != null) yield return (T)i.Value;
        }
    }
}
wefwfwefwe
Cache doesn't actually have an Items collection. Even if it did, this wouldn't work, because it would only return the type of DictionaryEntry.
Brian Vallelunga