2013-05-09 65 views
0

我有下面的类:LINQ GroupBy 3属性?

public class ProductInventory : Entity 
{ 
    public virtual Product Product { get; set; } 
    public DateTime ExpirationDate { get; set; } 
    public Manager Manager { get; set; } 
} 

和一类在我的ViewModels使用看起来像这样:

public class ProductInventoryCountModel 
{ 
    public Product Product { get; set; } 
    public DateTime ExpirationDate { get; set; } 
    public int Count { get; set; } 
} 

我想要得到的Dictionary<Manager, List<ProductInventoryCountModel>的输出,基本上由管理器显示产品然后到期日期以便我可以打印出看起来像这样的实际数据:

ManagerBoB 

--ProductA, Expires 8/15/13, Count: 10 
--ProductA, Expires 10/10/13, Count: 40 
--ProductB, Expires 6/13/13, Count: 30 

ManagerTim 

--ProductA, Expires 10/10/13, Count: 5 
--ProductB, Expires 5/25/13, Count: 10 
--ProductB, Expires 6/13/13, Count 40 

我会怎样wri在LINQ中查询这个查询时,从ProductInventory列表开始?我尝试了使用多个.GroupBy,但没有奏效。

回答

1

你说你想要一个Dictionary<Manager, List<ProductInventoryCountModel>>,所以我认为你必须做这样的事情:

var dictionary = 
    db.ProductInventory.GroupBy(x => new { x.Manager, x.Product, x.ExpirationDate }) 
     .ToDictionary(g => g.Key.Manager, 
        g => g.Select(x => new ProductInventoryCountModel 
            { 
             Product = x.Key.Product, 
             ExpirationDate = x.Key.ExpirationDate, 
             Count = x.Count() 
            }).ToList()); 
5

你需要按多个属性的对象:

list.GroupBy(p => new { p.Manager, p.Product.Name, p.ExpirationDate.Date }) 

这工作,因为匿名类型实现Equals()GetHashCode()按值进行比较。