title: LINQ Sum with GroupBy
body: <p>(Not sure if I even need GroupBy)</p>
  
  <p>My (simplified) tables:</p>
  
  <p><code>Products</code> (ProductID, Name, Code)<br />
  <code>Invoices</code> (InvoiceID, Number, IsPaid)<br />
  <code>Invoices_Products</code> (InvoiceID, ProductID, Quantity, Price) - the many-to-many linking table</p>
  
  <p>I need to show a list of Invoices_Products of paid Invoices grouped by the Product Code which sums (Quantity*Price).</p>
  
  <p>The code that I first use to get a collection that I can bind to the UI:</p>
  
  <pre><code>IEnumerable&lt;Invoices_Products&gt; invoices_products = db.Invoices_Products
  .Where(ip =&gt; ip.Invoice.IsPaid).DistinctBy(m =&gt; m.Product.Code);
  </code></pre>
  
  <p>I then iterate through this to bind it to the UI:</p>
  
  <pre><code>List&lt;BindableInvoiceProduct&gt; bindableInvoiceProducts = 
  new List&lt;BindableInvoiceProduct&gt;();
  
  foreach (var item in invoices_products)
  {
      decimal salesValue = db.Invoices_Products.Where(ip =&gt; ip.Invoice.IsPaid 
      &amp;&amp; ip.Product.Code == item.Product.Code).Sum(m =&gt; (m.Price * m.Quantity));
  
      bindableInvoiceProducts.Add(new BindableInvoiceProduct()
      {
          A = item.A,
          B = item.B,
          SalesValue = salesValue.ToString()
      });
  }
  </code></pre>
  
  <p>(The <code>DistinctBy</code> method there is from morelinq)</p>
  
  <p>Why does this not total correctly?</p>
  
  <p><strong>edit:</strong> </p>
  
  <p>Some data:</p>
  
  <p>Product - ProductID = 1, Name = 123, Code = A<br />
  Product - ProductID = 2, Name = 456, Code = A<br />
  Invoice - InvoiceID = 1, Number = INV123, IsPaid = True<br />
  Invoices_Products - InvoiceID = 1, ProductID = 1, Quantity = 10, Price = 100<br />
  Invoices_Products - InvoiceID = 1, ProductID = 2, Quantity = 10, Price = 200<br /></p>
  
  <p>Expected result:</p>
  
  <p>Code = A, SalesValue = 3000</p>