我有一个Product
课程:
class Product
{
public string Name { get; set; }
public DateTime ProductionDate { get; set; }
public int CategoryId { get; set; }
}
如果我有List<Product>
,我想GroupBy
和ProductionDate
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>>
。该对象是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
但它给了我以下错误:
{{1}}
答案 0 :(得分:2)
我认为问题是AddRange
没有返回列表,而且您已经分组,因此不需要Where
。
这应该足够了:
productsPerPeriodPerCategory = groupedProducts
.ToDictionary(p => p.categoryId,
p => p.Select(x => new Data()
{
xValue = x.prodDate,
yValue = x.amount.ToString()
}).ToList());
如果您不需要中间组
,您也可以在一步完成所有操作List<Product> products = GetAllProducts();
var groupedProducts = products.Groupby(p => new { p.ProductionDate, p.CategoryId })
.ToDictionary(
x => x.Key.CategoryId,
x => new Data()
{
xValue = x.Key.ProductionDate.ToString(),
yValue = x.Count().ToString()
});
答案 1 :(得分:1)
试试这个:
productsPerPeriodPerCategory =
groupedProducts
.GroupBy(p => p.categoryId)
.ToDictionary(
g => g.Key,
g =>
g.Select(
r =>
new Data {xValue = r.prodDate, yValue = r.amount.ToString()}));