title: Sum List of objects using Linq
body: <p>I have a Class:</p>
  
  <pre><code>public Class MyClass
  {
    public string name {get;set;}
    public double quantity {get; set;}
    public double price {get; set;}
    public double value {get; set;}
    public string id1 {get; set;}
    public string id2 {get; set;}
  }
  
  
  List&lt;MyClass&gt; myList = new List&lt;MyClass&gt;();
  </code></pre>
  
  <p>The list objects are then populated but the same name can have multiple entries. For example, here is my list overview:</p>
  
  <pre><code>[0] "stock A", 200.0, 20.0, 4000, "aa", "bb"
  [1] "stock A", 400.0, 20.0, 8000, "aa", "bb"
  [2] "stock B", 200.0, 20.0, 4000, "cc", "dd"
  [3] "stock A", 200.0, 19, 3800, "aa", "bb"
  [4] "stock C", 200.0, 20.0, 4000, "ee", "ff"
  </code></pre>
  
  <p>Currently I have the following code:</p>
  
  <pre><code>var groupedStockList = (from t in myList
    group t by new { t.name, t.price }
      into grp
      select new
      {
        grp.Key.name,
        grp.Key.price,
  
        Quantity = grp.Sum(x =&gt; x.quantity)
      }).ToList();
  </code></pre>
  
  <p>The result is that Stock A is grouped but 2 groups for 2 sets of prices, so I have a grouping of 600 stock A with a price of 20 and 200 stocks at a price of 19.</p>
  
  <p>I was thinking I have to go with the average price, i.e. <code>sum = (quantity * price) / total_quantity</code> but am lost as how to incorporate this in linq.</p>
  
  <p>Is there anyone who has an approach to this who can help please? I would like to keep ids 1 and 2 also in the list and just sort by name.</p>
  
  <p>Thanks.</p>
  
  <p>EDIT</p>
  
  <p>What I would like to return is this,</p>
  
  <pre><code>[0] "stock A", 800, 19.75, 15800, "aa", "bb"
  [1] "stock B", 200.0, 20.0, 4000, "cc", "dd"
  [2] "stock C", 200.0, 20.0, 4000, "ee", "ff"
  </code></pre>