微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – 匿名类型列表

这是我的代码

var personalInfoQuery = from t in crnnsupContext.Tombstones.Include("Provstate")
                        join n in crnnsupContext.NursingSchools 
                                     on t.NursingSchool equals n.SchoolID
                        where t.RegNumber == _username
                        select new { t,n };

然后我尝试将personalInfoQuery放入类似的列表中

List<> personalInfoResult = personalInfoQuery.ToList();

但如何在列表中表示匿名类型?

我需要将它插入缓存中
所以Cache.Insert(“personalInfo”,personalInfoQuery.ToList())
然后Cache [“personalInfo”]成为一个对象,我怎样才能从中读取数据呢?

解决方法

由于您的类型需要由多个方法使用(它需要由一个方法创建并由另一个方法读取),因此使用匿名类型是不合适的.只需创建一个简单的类型:

public class TombstoneNursingSchool
{
    public Tombstone Tombstone { get; set; }
    public NursingSchool NursingSchool { get; set; }
}

像这样创建它:

var personalInfoQuery = from t in crnnsupContext.Tombstones.Include("Provstate")
                        join n in crnnsupContext.NursingSchools 
                                     on t.NursingSchool equals n.SchoolID
                        where t.RegNumber == _username
                        select new TombstoneNursingSchool {
                            Tombstone = t,NursingSchool = n 
                        };

列出这样的列表:

List<TombstoneNursingSchool> personalInfoResult = personalInfoQuery.ToList();

像这样把它放在缓存中:

Cache.Insert("personalInfo",personalInfoQuery.ToList())

从缓存中取出并按如下方式读取:

foreach(var tn in (List<TombstoneNursingSchool>)Cache["personalInfo"])
{
     // do something with tn.Tombstone and tn.NursingSchool
}

匿名类型在单个方法中很方便,但它们并不适合所有情况.如果您需要,请不要害怕制作命名类型.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐