GroupBy query by Linq.Expressions and Lambdas
<p>What I need is to represent this query via Linq.Expressions:</p>

<pre><code>db.Documents.GroupBy(a =&gt; 1).Select(b =&gt; b.Sum(c =&gt; c.Amount) });
</code></pre>

<p>Here is what I have so far:</p>

<pre><code>IQueryable&lt;Document&gt; data = db.Documents;

ParameterExpression pe = Expression.Parameter(typeof(Document), "doc");

Expression groupBy = Expression.Call(
    typeof(Queryable),
    "GroupBy",
    new Type[] { typeof(Document), typeof(int) },
    data.Expression,
    Expression.Lambda(Expression.Constant(1), pe));

ParameterExpression peg = Expression.Parameter(typeof(IGrouping&lt;int, Document&gt;), "group");

Expression select = Expression.Call(
    typeof(Queryable),
    "Select",
    new Type[] { typeof(IGrouping&lt;int, Document&gt;), typeof(int) },
    groupBy,
    Expression.Lambda(Expression.Property(peg, "Key"), peg));

foreach (var item in data.Provider.CreateQuery(select)) { ... }
</code></pre>

<p>This was implementation of:</p>

<pre><code>db.Documents.GroupBy(a =&gt; 1).Select(b =&gt; b.Key });
</code></pre>

<p>And it works perfectly. Now, I want to aggregate a sum instead of accessing the key of group. </p>

<p>That is where it gets tricky for me. I was thinking something like this:</p>

<pre><code>ParameterExpression pe1 = Expression.Parameter(typeof(Document), "other");

Expression sum = Expression.Call(
    typeof(Queryable),
    "Sum",
    new Type[] { typeof(Document) },
    peg,
    Expression.Lambda(Expression.Property(pe1, "Amount"), pe1));
</code></pre>

<p>Also, for Sum function in </p>

<pre><code>...b.Sum(c =&gt; c.Amount)
</code></pre>

<p>Intellisense gives signature:</p>

<pre><code>IEnumerable&lt;Document&gt;.Sum&lt;Document&gt;(Func&lt;Document, decimal&gt; selector)
</code></pre>

<p>While for:</p>

<pre><code>db.Documents.Sum(a =&gt; a.Amount)
</code></pre>

<p>I get:</p>

<pre><code>IQueryable&lt;Document&gt;.Sum&lt;Document&gt;(Expression&lt;Func&lt;Document, decimal&gt;&gt; selector)
</code></pre>

<p>Selector is Func in one version and Expression in other. I don't know how to handle Func in Linq Expressions. Maybe Intellisense is wrong?</p>

<p>Expression for source of aggregation is my biggest issue. By looking at:</p>

<pre><code>...b.Sum(c =&gt; c.Amount)
</code></pre>

<p>i would presume that b should be IGrouping (ParameterExpression of 'select'), and that should be the source for Sum, but that won't compile. 
I don't know what else to try?</p>

<p>Here is how last select expression should look like: </p>

<pre><code>Expression Select = Expression.Call(
    typeof(Queryable),
    "Select",
    new Type[] { typeof(IGrouping&lt;int, Document&gt;), typeof(decimal?) },
    GroupBy,
    Expression.Lambda(sum, peg));
</code></pre>

<p>But I can't even reach this point, because of the failed 'sum' expression. </p>

<p>Any pointers would be appreciated.</p>

<p>Regards, </p>