Reputation: 10478
I've got the following class:
public class ProductInventory : Entity
{
public virtual Product Product { get; set; }
public DateTime ExpirationDate { get; set; }
public Manager Manager { get; set; }
}
and a class used in my ViewModels that looks like so:
public class ProductInventoryCountModel
{
public Product Product { get; set; }
public DateTime ExpirationDate { get; set; }
public int Count { get; set; }
}
I want to get an output of Dictionary<Manager, List<ProductInventoryCountModel>
that basically displays Products by manager and then by expiration date so that I can print out actual data looking something like this:
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
how would I write this query in LINQ when starting with a list of ProductInventory
? I tried using multiple .GroupBy
but that didn't work.
Upvotes: 0
Views: 148
Reputation: 149050
You stated that you want a Dictionary<Manager, List<ProductInventoryCountModel>>
, so I think you'd have to do something like this:
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());
Upvotes: 1
Reputation: 887857
You need to group by an object with multiple properties:
list.GroupBy(p => new { p.Manager, p.Product.Name, p.ExpirationDate.Date })
This works because anonymous types implement Equals()
and GetHashCode()
to compare by value.
Upvotes: 5