Casting匿名类型已知模型

时间:2012-06-20 15:28:04

标签: asp.net-mvc casting controller ienumerable

我的模型类是这样的:

Public class abc {

         public string p1 get; set;
         public string p2 get; set;
}

我试图像这样施展

IEnumerable<abc> data= ( IEnumerable<abc>) (from d in d.GetAll()
                       select new {
                        p1= d.p1,
                        p2= d.p2
                     }).Distinct();

它给了我错误:

Unable to cast object of type <DistinctIterator>

请告知

1 个答案:

答案 0 :(得分:3)

您无法直接将匿名类型转换为已知类型。这样做:

IEnumerable<abc> data = from d in d.GetAll()
                    select new abc() {
                     p1 = d.p1,
                     p2 = d.p2
                  }).Distinct();

并在必要时创建IEqualityComparer以与您的Distinct调用一起使用。有关使用Distinct实现IEqualityComparer的示例,请参阅Enumerable.Distinct Method (IEnumerable, IEqualityComparer)