System.Runtime.Caching returns wrong count when using OfType<T>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
MemoryCache.Default.Add("C1", new Customer { Name = "C1" }, DateTime.Now.AddDays(1));
MemoryCache.Default.Add("C2", new Customer { Name = "C2" }, DateTime.Now.AddDays(1));
MemoryCache.Default.Add("C3", new Customer { Name = "C3" }, DateTime.Now.AddDays(1));
Console.WriteLine("Total Cached Objects: {0}", MemoryCache.Default.GetCount());
Console.WriteLine("Total cached objects of type Customer: {0}", MemoryCache.Default.OfType<Customer>().Count());
Console.Read();
}
}
public class Customer
{
public string Name { get; set; }
}
}
I am adding 3 Objects of type Customer to the MemoryCache and then trying to filter the MemoryCache to retrieve only those objects which are of type Customer.
After 开发者_StackOverflow中文版executing the above code, i was expecting "Total cached objects of type Customer" to be 3 but it returns 0.
Anyone can point me out what is wrong here?
The declaration of the relevant method of MemoryCache is
IEnumerator<KeyValuePair<string, Object>> GetEnumerator()
That method returns a list of KeyValue pairs, you are expecting just the Values.
It appears you need something like
// utested
MemoryCache.Default.Select(x => x.Value).OfType<Customer>().Count()
精彩评论