2013-05-08 57 views
1

我正在使用.NET MVC4和實體框架開發一個新項目。我有一個產品表,我試圖用分組來選擇產品。無法使用LINQ填充表格的分組列表

我的模型:

public class Cart 
{ 
    public long Index { get; set; } 
    public List<Products> ProductList = new List<Products>(); 
    public int ItemCount { get; set; } 
    public decimal Total { get; set; } 
} 

我的查詢:

var result = from p in productList 
      group p by p.id into grp 
      select new 
      { 
       Index = grp.Key, 
       ProductList = grp.ToList<Products>(), 
       ItemCount = grp.Count(), 
       Total = grp.Sum(w => w.price) 
      }; 

然後,我想申請結果車的名單。但我在某個時候失敗了。請你能幫我做到這一點。

回答

2

您需要通過您的select

var result = from p in productList 
      group p by p.id into grp 
      select new Cart //<-- here 
      { 
       Index = grp.Key, 
       ProductList = grp.ToList<Products>(), 
       ItemCount = grp.Count(), 
       Total = grp.Sum(w => w.price) 
      }; 

現在resultIEnumerable<Cart>類型的指定返回的類型。您可以添加一個額外的ToList()使其成爲List<Cart>

List<Cart> lst = result.ToList();