2012-06-20 133 views
0

我的模型類是這樣的:鑄造匿名類型稱爲模型

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> 

請告知

+0

在stackoverflow快速搜索已透露這篇文章可能有所幫助:[Linq類型轉換泛型類型](http://stackoverflow.com/questions/8204930/linq-type-conversion-on-generic-types ) – Jeremy

回答

3

您不能直接施放匿名類型爲已知類型。做到這一點,而不是:

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

,如果需要創建的IEqualityComparer與鮮明的呼叫使用。有關使用Distinct實現IEqualityComparer的示例,請參見Enumerable.Distinct Method (IEnumerable, IEqualityComparer)

+0

謝謝,它工作! – Learner