2013-05-09 58 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()按值進行比較。