2011-10-23 50 views
1

限制LINQ的結果列我有返回晚餐爲GridView控件

public static System.Collections.Generic.List<Dinner> GetDinners() 
{ 
    using (DataClassesDataContext h = new DataClassesDataContext()) 
    { 
     var query = (from dins in h.Dinners 
        where dins.Title == "New York" 
        select dins); 
     return query.ToList(); 
    } 
} 

我用這個在我的aspx頁面來填充網格在我的業務層,這種靜態方法。

protected void Page_Load(object sender, EventArgs e) 
{ 
    GridView1.DataSource = BusinessLayer.GetDinners(); 
    GridView1.DataBind(); 
} 

我想限制業務層級的返回列。 我可以在Linq這樣做。

 var query = (from dins in h.Dinners 
        where dins.Title == "New York" 
        select new { dins.Title, dins.DinnerID }); 

但後來我得到一個匿名類型的錯誤,這是有道理的,但我該如何解決這個問題?

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 
'System.Collections.Generic.List<Dinner> 

回答

2

除非返回類型是動態的,否則不能從方法返回匿名類型。否則,您需要爲選擇語句中的結果和項目創建一個單獨的類。

要麼更改簽名如下:

public static System.Collections.Generic.List<dynamic> GetDinners() 
{ 

然後回到你的查詢,像這樣:

return query.ToList().Cast<dynamic>().ToList(); 

或者創建一個類,並返回,而不是使用匿名類型的該列表。

+0

非常感謝 – Hoody