我根据stackoverflow问题回答建议从Linq查询结果创建了一个字典:A dictionary where value is an anonymous type in C#
var intToAnon = sourceSequence.ToDictionary(
e => e.Id,
e => new { e.Column, e.Localized });
我已将此新对象添加到我的ASP.NET缓存中。如何从缓存中读取它(HttpContext.Current.Cache.Add
)?我想我需要反思,但不知道该怎么做。
有什么想法吗?
谢谢
答案 0 :(得分:1)
要检索匿名类型,您需要使用反射或cast-by-example,在这种情况下,这两者都不是一个好主意。
相反,要么创建自己的自定义类型来保存数据,要么使用其中一种内置Tuple
类型:
// 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;
然后,当您从缓存中获取对象时,只需转换为相应的Tuple
类型:
// i'm assuming here that Id is Int32, Column is String, and Localized is Boolean
var dict = (Dictionary<int, Tuple<string, bool>>)Cache["yourCacheKey"];