-1

I created a dictionary from a Linq query result as suggested from stackoverflow questions answer: A dictionary where value is an anonymous type in C#

var intToAnon = sourceSequence.ToDictionary(
e => e.Id,
e => new { e.Column, e.Localized });

I have added this new object into my ASP.NET cache. How can I read it from the cache (HttpContext.Current.Cache.Add)? I imagine I need reflection but not sure how to go about it.

Any idea?

Thanks

Community
  • 1
  • 1
Meelfan Bmfp
  • 605
  • 1
  • 7
  • 30
  • possible duplicate of [Accessing C# Anonymous Type Objects](http://stackoverflow.com/questions/713521/accessing-c-sharp-anonymous-type-objects) – nawfal Jun 28 '14 at 08:56

1 Answers1

1

To retrieve an anonymous type you'll either need to use reflection or cast-by-example, neither of which are a good idea in this case.

Instead, either create your own custom type to hold the data, or use one of the built-in Tuple types:

// dict will be a Dictionary<TId, Tuple<TColumn, TLocalized>>
// where TId, TColumn and TLocalized are the actual types of those properties
var dict = sourceSequence.ToDictionary(e => e.Id,
                                       e => Tuple.Create(e.Column, e.Localized));
Cache["yourCacheKey"] = dict;

Then when you get the object from the cache just cast to the appropriate Tuple type:

// i'm assuming here that Id is Int32, Column is String, and Localized is Boolean
var dict = (Dictionary<int, Tuple<string, bool>>)Cache["yourCacheKey"];
Community
  • 1
  • 1
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • Thanks, for the answer, could you show how one could use Tuple instead of the dictionary projection? I first attempted this with no success (lack of understanding) – Meelfan Bmfp Jan 31 '12 at 12:08
  • Great, this looks like what i need.... Thousands thanks. I Did not want to create a custom type for this and i think your suggestion does exactly what i was looking for. – Meelfan Bmfp Jan 31 '12 at 12:14
  • I 'm having one more issue with this question. My sequence returned need to be grouped before being added to the dictionary. When doing so, i can not add it to the dictionary way show suggested above. How can i do this? I'm currently receiving an exception "An item with the same key has already been added." – Meelfan Bmfp Feb 01 '12 at 09:26