【问题标题】:Casting Anonymous type known model铸造匿名型已知模型
【发布时间】:2012-06-20 15:28:03
【问题描述】:

我的模型类是这样的:

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>

请指教

【问题讨论】:

标签: asp.net-mvc casting controller ienumerable


【解决方案1】:

您不能直接将匿名类型强制转换为已知类型。改为这样做:

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)

【讨论】:

    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多