我有一Product
堂课:
class Product
{
public string Name { get; set; }
public DateTime ProductionDate { get; set; }
public int CategoryId { get; set; }
}
如果我有一个List<Product>
and 我想GroupBy
通过ProductionDate
and CategoryId
。我愿意:
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()
});
对于每一个categoryId
,我都想知道products
在特定的prodDate
. 所以我创建了一个Dictionary
对象,对于每个categoryId
键,我存储prodDate
和amount
。对象是一个Dictionary<string, List<Data>>
with
class Data
{
public string xValue { get; set; }
public string yValue { get; set; }
}
为此,我尝试了:
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()));
但它给了我以下错误:
Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<string>' because it is not a delegate type