title: Linq group by with parent object
body: <p>How do I group so that I don't loose the parent identifier.</p>
  
  <p>I have the following</p>
  
  <pre><code>        var grouped = mymodel.GroupBy(l =&gt; new { l.AddressId })
              .Select(g =&gt; new
              {
                  AddressId = g.Key.AddressId,
                  Quotes = g.SelectMany(x =&gt; x.Quotes).ToList(),
              }).ToList();
  </code></pre>
  
  <p>this returns </p>
  
  <blockquote>
    <p>{ AddressId1, [Quote1, Quote2, Quote3...]}</p>
    
    <p>{ AddressId2, [Quote12, Quote5, Quote8...]}</p>
  </blockquote>
  
  <p>Now I would like to group these by Quote.Code and Quote.Currency, So that Each address has 1 Object-Quote (that is if all 4 quotes belonging to the address have the same Code and Currency). I would like the sum of Currency in that object.</p>
  
  <p>This works, but I can't get how to add Address to this result:</p>
  
  <pre><code>        var test = grouped.SelectMany(y =&gt; y.Quotes).GroupBy(x =&gt; new { x.Code, x.Currency }).Select(g =&gt; new 
          {
              test = g.Key.ToString()
          });}
  </code></pre>
  
  <p>this gives compile error, whenever i try to add AddressId to result:</p>
  
  <pre><code>        var test1 = grouped.SelectMany(y =&gt; y.Quotes, (parent, child) =&gt; new { parent.AddressId, child }).GroupBy(x =&gt; new { x.Provider, x.Code, x.Currency, x.OriginalCurrency }).Select(g =&gt; new
          {
              test = g.Key.ToString(),
              Sum = g.Sum(x =&gt; x.Price)
          });
  </code></pre>
  
  <p>compiler error as well:</p>
  
  <pre><code>        var test1 = grouped.Select(x =&gt; new { x.AddressId, x.Quotes.GroupBy(y =&gt; new { y.Provider, y.Code, y.Currency, y.OriginalCurrency }).Select(g =&gt; new
          {
              addr = x.AddressId,
              test = g.Key.ToString(),
              Sum = g.Sum(q =&gt; q.Price)
          };
  </code></pre>