I have a Product class:
class Product
{
public string Name { get; set; }
public DateTime ProductionDate { get; set; }
public int CategoryId { get; set; }
}
If I have a List<Product> and I want to GroupBy by ProductionDate and CategoryId. I do:
List<Product> products = GetAllProducts();
var groupedProducts = products.Groupby(p => new { p.ProductionDate, p.CategoryId })
.Select(pgroup => new {
prodDate = pgroup.Key.ProductionDate.ToString(),
categoryId = pgroup.Key.CategoryId.ToString(),
amount = pgroup.Count()
});
For each categoryId I would like to have how many products have been produced in a specific prodDate. So I create a Dictionary object where for each categoryId key, I store the prodDate and the amount. The object is a Dictionary<string, List<Data>> with
class Data
{
public string xValue { get; set; }
public string yValue { get; set; }
}
To do so I tried:
Dictionary<string, List<Data>> productsPerPeriodPerCategory = new Dictionary<string, List<Data>>();
productsPerPeriodPerCategory = groupedProducts
.ToDictionary(p => p.categoryId,
p => new List<Data>().AddRange(
groupedProducts.Where(g => g.categoryId == p.categoryId)
.Select(x => new Data()
{
xValue = x.prodDate,
yValue = x.amount.ToString()
}).ToList()));
But it gives me the following error:
Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<string>' because it is not a delegate type
Try this: