2009-06-02 98 views
0

爲什麼沒有這個工作,以及如何解決?接口和鑄造列表

public interface ITheInterface 
{ 

    string a{get;set;} 
    string b{get;set;} 
} 

public class SomeObject: ITheInterface 
{ 
    string a{get;set;} 
    string b{get;set;} 
    ... 
} 

public class SomeGroup 
{ 
    ITheInterface Result; 
    ... 
} 

var results= from y in dc.Groups 
       where y.id==1 
       select new SomeGroup 
         { 
         Result= (from x in dc.Objects 
         select new SomeObject{... } 
         ).SingleOrDefault(), 
         } 

return results.ToList(); 

無法從System.Collections.Generic.List類型轉換爲界面

+1

爲什麼沒有工作?你遇到了什麼錯誤? – 2009-06-02 00:34:01

+0

請給出一個簡短的*完整的*程序,否則我們不能告訴發生了什麼問題。 – 2009-06-02 05:32:31

回答

1

我認爲你的問題是與Results.ToList()電話嗎?它會失敗,因爲ITheInterface不支持ToList()。您正在LINQ查詢上調用SingleOrDefault(),該查詢爲您提供單個項目。在單個項目上調用ToList()沒有任何意義。

相反,如果你的代碼這樣寫的:

IEnumerable<SomeObject> Results = from x in dc.Objects 
            select new SomeObject{... }; 

然後,Results.ToList()會給你一個List<SomeObject>

如果您實際尋找的是一個List<ITheInterface>相反,你可以這樣做:

Results.Cast<ITheInterface>().ToList() 
0

結果是一個單一的對象; ToList()僅適用於Enumerables。

您需要編寫return new List { Results };(這使用集合初始值設定項)或免除對SingleOrDefault的調用並聲明結果爲IEnumerable<ITheInterface>

如果你只想要一個對象,爲什麼你要返回一個List?

0

除了其他的答案,當你實現一個接口,您必須public宣佈該成員函數:

public class SomeObject: ITheInterface 
{ 
    public string a{get;set;} 
    public string b{get;set;} 
    ... 
} 
0

你想說

SomeGroup result = results.SingleOrDefault() 
return result; 

這是因爲返回類型你的方法是SomeGroup(我推斷)