Search code examples
c#linqmemorycache

MemoryCache.Default remove using LINQ


Is there a way i can remove objects from MemoryCache.Default using LINQ query like this:

MemoryCache.Default.Select(c => c.Value).OfType<CachedObjectType>().ToList().RemoveAll(k => k.ZipCode == "11111");

This doesnt remove the objects from the MemoryCache.Default instance.


Solution

  • Since you are projecting you are working with a new list, not the original one, LINQ is not the right tool for mutation - also you need the key of the item to remove, not the value.

    This should work:

    var itemsToRemove = MemoryCache.Default
                                   .Where( x=> x.Value is CachedObjectType &&
                                              (x.Value as CachedObjectType).ZipCode == "11111")
                                   .Select(x=> x.Key)
    foreach(var key in itemsToRemove)
        MemoryCache.Default.Remove(key);