2013-05-08 53 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();