【发布时间】:2012-11-19 18:12:36
【问题描述】:
我有以下Product 类:
public class Product
{
public string Name { get; set; }
public float Price { get; set; }
public int? CategoryId { get; set; }
}
现在我必须计算每个CategoryId 有多少Product,并将它们放在Dictionary<int, int> 中。因此:
IQueryable<Product> products = _productServices.GetAll(); //return IQueryable<Product>
Dictionary<int, int> productDict = products.ToList()
.GroupBy(p => p.CategoryId)
.ToDictionary(pgroup => pgroup.key, pgroup => pgroup.Count());
问题是我从ToDictionary() 获得了Dictionary<int?, int>。即使我通过放置Where(p => p.CategoryId != null) 来预过滤空值,我也不会将CategoryId 的类型更改为int。我也尝试过创建匿名类型:
products.ToList()
.GroupBy(p => p.CategoryId)
.Select(p => new { p.key ?? -1, p.Count() }
.ToDictionary(pgroup => pgroup.key, pgroup => pgroup);
但它给出了Invalid anonymous type member declarator 错误。我还尝试删除 ToList() 但没有运气。我用谷歌搜索了一下,没有发现有人遇到这个问题,尽管我认为这种情况可能很常见,尤其是在使用 EF 和 databases 时。有人有解决办法吗?
【问题讨论】:
-
试试
p.CategoryId.Value(不可为空)而不是p.CategoryId?