我有下面这个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);
但是它会报错:无效的匿名类型成员声明
。我也试过去掉ToList()
,但没有成功。我在谷歌上搜了一下,没有找到任何人遇到这个问题,虽然我认为这种情况可能经常发生,尤其是在使用EF和数据库时。有人有解决方案吗?
p.CategoryId.Value
(非空)而不是p.CategoryId
? - user