title: How to build a Func lambda expression dynamically in C#
body: <p>I have an ElasticSearch database in which I want to perform an aggregation.
  I'm using NEST and lambda expression to create the query.</p>
  
  <p>However, I need to perform the aggregation on multiple fields of the same document  (channel1 and channel2) at the same time.
  Currently I have 2 channels so my query works fine over them.  </p>
  
  <pre><code>    var res = elasticClient.Search&lt;DataRecord&gt;(s =&gt; s
          .Index(ElasticIndexName)
          .Aggregations(a =&gt; a
              .DateHistogram("mydoc", h =&gt; h
                  .Aggregations(ag =&gt; ag.Average("avg1", b =&gt; b.Field("channel1")).Average("avg2", b =&gt; b.Field("channel2")))
              )
          )
      );
  </code></pre>
  
  <p>The problem is that the no. of channels could be different, maybe three or four or whatever so I'd like to have my Func below</p>
  
  <pre><code>ag =&gt; ag.Average("avg1", b =&gt; b.Field("channel1")).Average("avg2", b =&gt; b.Field("channel2"))
  </code></pre>
  
  <p>to be dynamically created (like you do on a SQL query for example) because the no. of channels is known only at runtime.</p>
  
  <p>E.g.
  If I have four channels the query should be like:</p>
  
  <pre><code>  var res = elasticClient.Search&lt;DataRecord&gt;(s =&gt; s
          .Index(ElasticIndexName)
          .Aggregations(a =&gt; a
              .DateHistogram("mydoc", h =&gt; h
                  .Aggregations(ag =&gt; ag.Average("avg1", b =&gt; b.Field("channel1")).Average("avg2", b =&gt; b.Field("channel2")).Average("avg3", b =&gt; b.Field("channel3")).Average("avg4", b =&gt; b.Field("channel4")))
              )
          )
      );
  </code></pre>
  
  <p>So basically I need some kind of for loop in which I can build the lambda expression dinamically</p>