score:7

Accepted answer

That's because CategoryId is a nullable. So you need to select it's Value property first:

products.ToList()
        .Where(p => p.CategoryId.HasValue)
        .Select(p => p.CategoryId.Value)
        .GroupBy(i => i)
        .ToDictionary(g => g.Key, g => g.Count());

score:4

How about this?

.ToDictionary(pgroup => pgroup.Key ?? -1, pgroup => pgroup.Count());

And regarding your syntax error with the anonymous type, the correct syntax is as follows:

.Select(p => new { Key = p.Key ?? -1, Count = p.Count() })

score:5

Simply use

products.ToList()
    .GroupBy(p => p.CategoryId)
    .Where(pgroup => pgroup.Key.HasValue)
    .ToDictionary(pgroup => pgroup.Key.Value, pgroup => pgroup.Count());

score:0

You need to filter out the null values, and then use the .Value property of the int? as the grouping key:

products.ToList()
        .Where(p => p.CategoryId.HasValue)
        .GroupBy(p => p.CategoryId.Value)
        .ToDictionary(pgroup => pgroup.key, pgroup => pgroup.Count());

Related Articles