title: How to use GroupBy and Sum in LINQ?
body: <p>I'm struggling with GroupBy and Sum in the following query using SelectMany. Could someone show me how to sum two fields as well as how to group by and order by several fields.</p>
  
  <pre><code>var Rows = allData.SelectMany(u =&gt; u._rows.Select(t =&gt; new
  {
    OA = t[4],
    CD = t[5],
    PD = t[0],
    DS = Convert.ToInt32(t[9]),
    CS = Convert.ToInt32(t[10])
  }))
  // Pseudo-code:
  //.GroupBy(CD)
  //.GroupBy(OA)
  //.GroupBy(PD)
  //.Sum(u=&gt; u.DS)
  //.Sum(u =&gt; u.CS)
  .OrderBy(u =&gt; u.CD)
  .ThenBy(u =&gt; u.OA)
  .ThenBy(u =&gt; u.PD)
  .ToList();
  </code></pre>
  
  <p>Object:</p>
  
  <pre><code>List&lt;DataProperty&gt; allData = new List&lt;DataProperty&gt;();         
  </code></pre>
  
  <p>DataProperty consists of </p>
  
  <pre><code>private readonly Dictionary&lt;string, string&gt; _headers = new Dictionary&lt;string, string&gt;(); 
  private readonly List&lt;string[]&gt; _rows = new List&lt;string[]&gt;();
  </code></pre>
  
  <p>The original query before the C# rewrite from ColdFusion:</p>
  
  <blockquote>
  <pre><code>SELECT 
  OA,
  CD,
  PD,               
  sum(DS) as DS
  sum(CS) as CS
  FROM qDistinct
  GROUP BY 
  CD,
  OA,
  PD
  ORDER BY 
  ucaseCD,
  OA,
  PD
  </code></pre>
  </blockquote>
  
  <p>If the GroupBy is coded differently in the following query without Sum, could you also please show me how to do it?</p>
  
  <pre><code>var Rows = allData.SelectMany(u =&gt; u._rows.Select(t =&gt; new
  {
    OA = t[4],
    PD = t[0]      
  }))
  // Pseudo-code:
  //.GroupBy(OA)
  //.GroupBy(PD)   
  .OrderBy(u =&gt; u.OA)
  .ThenBy(u =&gt; u.PD)
  .ToList();
  </code></pre>