I have the following Product class:
public class Product
{
public string Name { get; set; }
public float Price { get; set; }
public int? CategoryId { get; set; }
}
Now I have to count how many Product I have for each CategoryId and place them in a Dictionary<int, int>. Therefore:
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());
The problem is that I obtain a Dictionary<int?, int> from the ToDictionary(). Even if I pre-filter the null values by placing Where(p => p.CategoryId != null) I do not change the type of CategoryId to int. I also tried to create and anonymous type:
products.ToList()
.GroupBy(p => p.CategoryId)
.Select(p => new { p.key ?? -1, p.Count() }
.ToDictionary(pgroup => pgroup.key, pgroup => pgroup);
But it gives an Invalid anonymous type member declarator error. I also tried to remove the ToList() but no luck. I google it a bit and I haven’t found anybody having this issue, although I think this situation might be frequent, especially when working with EF and databases. Anybody has a solution?
That’s because
CategoryIdis a nullable. So you need to select it’sValueproperty first: