title: Sum nested values with Linq
body: <p>Simple problem: I have Users that can have many Orders that can have many Products.  What does the Linq (lambda) query look like to get a User's grand total of all Product.Price values?</p>
  
  <p>I've tried this:</p>
  
  <pre><code>int total = users.Sum(u =&gt; u.Orders.Sum(o =&gt; o.Products.Sum(p =&gt; p.Price)));
  </code></pre>
  
  <p>But it's giving me:</p>
  
  <blockquote>
    <p>The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.</p>
  </blockquote>
  
  <p>Of course, a user may not have any orders, and an order may not have any products. But Product.Price is not a nullable value.  </p>
  
  <p>So I tried this, thinking it was choking on empty collections:</p>
  
  <pre><code>int total = users.Sum(u =&gt; u.Orders.Sum(o =&gt; o.Products.Sum(p =&gt; p.Price) ?? 0) ?? 0) ?? 0;
  </code></pre>
  
  <p>But it's throwing compile errors, saying the left side of the <code>??</code> is not nullable.</p>
  
  <p>What am I doing wrong?</p>
  
  <p>Thanks in advance.</p>
  
  <p>UPDATE: A working version of my examples above after using Marc's logic from his answer:</p>
  
  <pre><code>int total = users.Sum(u =&gt; u.Orders.Sum(o =&gt; o.Products.Sum(p =&gt; (int?)p.Price))) ?? 0;
  </code></pre>