Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through httpcache c#

On VB.NET I can do things like this to write out all the keys in the cache:

Dim oc As HttpContext = HttpContext.Current

For Each c As Object In oc.Cache
    oc.Response.Write(c.Key.ToString())
Next

Although the .Key doesn't come up in Intellisense the code works just fine.

How do I do the same in c#?

HttpContext oc = HttpContext.Current;
foreach (object c in oc.Cache) 
{
    oc.Response.Write(c.key.ToString());
}

It doesn't like the .key. bit. I'm at a loss here. Any ideas how to access the key in this way?

like image 323
Quizzed2011 Avatar asked Nov 21 '11 10:11

Quizzed2011


2 Answers

Almost right - it's a capital K for Key, not lower case. C# is case sensitive.

Additionally, object doesn't have a Key member. In C# you can use implicit type inference with the var keyword as well. This will work if the underlying inferred type has a Key member:

HttpContext oc = HttpContext.Current;

foreach (var c in oc.Cache) 
{
    oc.Response.Write(c.Key.ToString());
}

In this case, Cache doesn't have a Key member, so you need to dig deeper, using the IDictionaryEnumerator returned by the GetEnumerator method of Cache:

HttpContext oc = HttpContext.Current;

IDictionaryEnumerator en = oc.Cache.GetEnumerator();
while(en.MoveNext())
{
    oc.Response.Write(en.Key.ToString());
}
like image 72
Oded Avatar answered Nov 13 '22 19:11

Oded


Below code snap is working fine:

HttpContext oc = HttpContext.Current;
foreach (var c in oc.Cache)        
{
   oc.Response.Write(((DictionaryEntry)c).Key.ToString());
}

Thanks for your time

like image 10
Elias Hossain Avatar answered Nov 13 '22 20:11

Elias Hossain