title: Convert Dictionary<int, int?> to Dictionary<int, int> by skipping null values with LINQ
body: <p>I have the following <code>Product</code> class:</p>
  
  <pre><code>public class Product
  {
      public string Name { get; set; }
      public float Price { get; set; }     
      public int? CategoryId { get; set; }
  }
  </code></pre>
  
  <p>Now I have to count how many <code>Product</code> I have for each <code>CategoryId</code> and place them in a <code>Dictionary&lt;int, int&gt;</code>. Therefore:</p>
  
  <pre><code>IQueryable&lt;Product&gt; products = _productServices.GetAll(); //return IQueryable&lt;Product&gt;
  
  Dictionary&lt;int, int&gt; productDict =  products.ToList()
                                              .GroupBy(p =&gt; p.CategoryId)
                                              .ToDictionary(pgroup =&gt; pgroup.key, pgroup =&gt; pgroup.Count());
  </code></pre>
  
  <p>The problem is that I obtain a <code>Dictionary&lt;int?, int&gt;</code> from the <code>ToDictionary()</code>. Even if I pre-filter the null values by placing <code>Where(p =&gt; p.CategoryId != null)</code> I do not change the type of <code>CategoryId</code> to <code>int</code>. I also tried to create and anonymous type:</p>
  
  <pre><code>products.ToList()
          .GroupBy(p =&gt; p.CategoryId)
          .Select(p =&gt; new { p.key ?? -1, p.Count() }  
          .ToDictionary(pgroup =&gt; pgroup.key, pgroup =&gt; pgroup);
  </code></pre>
  
  <p>But it gives an <code>Invalid anonymous type member declarator</code> error. I also tried to remove the <code>ToList()</code> 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 <strong>EF</strong> and <strong>databases</strong>. Anybody has a solution?</p>