title: Linq: GroupBy, Sum and Count
body: <p>I have a collection of products</p>
  
  <pre><code>public class Product {
  
     public Product() { }
  
     public string ProductCode {get; set;}
     public decimal Price {get; set; }
     public string Name {get; set;}
  }
  </code></pre>
  
  <p>Now I want to group the collection based on the product code and return an object containing the name, the number or products for each code and the total price for each product.</p>
  
  <pre><code>public class ResultLine{
  
     public ResultLine() { }
  
     public string ProductName {get; set;}
     public string Price {get; set; }
     public string Quantity {get; set;}
  }
  </code></pre>
  
  <p>So I use a GroupBy to group by ProductCode, then I calculate the sum and also count the number of records for each product code. </p>
  
  <p>This is what I have so far: </p>
  
  <pre><code>List&lt;Product&gt; Lines = LoadProducts();    
  List&lt;ResultLine&gt; result = Lines
                  .GroupBy(l =&gt; l.ProductCode)
                  .SelectMany(cl =&gt; cl.Select(
                      csLine =&gt; new ResultLine
                      {
                          ProductName =csLine.Name,
                          Quantity = cl.Count().ToString(),
                          Price = cl.Sum(c =&gt; c.Price).ToString(),
                      })).ToList&lt;ResultLine&gt;();
  </code></pre>
  
  <p><strong>For some reason, the sum is done correctly but the count is always 1.</strong></p>
  
  <p>Sampe data:</p>
  
  <pre><code>List&lt;CartLine&gt; Lines = new List&lt;CartLine&gt;();
              Lines.Add(new CartLine() { ProductCode = "p1", Price = 6.5M, Name = "Product1" });
              Lines.Add(new CartLine() { ProductCode = "p1", Price = 6.5M, Name = "Product1" });
              Lines.Add(new CartLine() { ProductCode = "p2", Price = 12M, Name = "Product2" });
  </code></pre>
  
  <p>Result with sample data:</p>
  
  <pre><code>Product1: count 1   - Price:13 (2x6.5)
  Product2: count 1   - Price:12 (1x12)
  </code></pre>
  
  <p>Product 1 should have count = 2!</p>
  
  <p>I tried to simulate this in a simple console application but there i got the following result:</p>
  
  <pre><code>Product1: count 2   - Price:13 (2x6.5)
  Product1: count 2   - Price:13 (2x6.5)
  Product2: count 1   - Price:12 (1x12)
  </code></pre>
  
  <p>Product1: should only be listed once...
  The code for the above can be found on pastebin: <a href="http://pastebin.com/cNHTBSie">http://pastebin.com/cNHTBSie</a></p>