MemoryCache.Default removes LINQ usage

Is there a way to remove objects from MemoryCache.Default using a LINQ query as follows:

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

This does not remove objects from the MemoryCache.Default instance.

+3
source share
1 answer

Since you are projecting, you are working with a new list and not with the original, LINQ is not a suitable tool for mutation - you also need a key to delete, not a 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);
+5
source

All Articles