title: How can I invoke several clients' async methods and aggregate the results into one task generically?
body: <p>The following code is intended to reduce redundant code by allowing you to generically invoke the same selector on a set of "getters" (data retrieval clients) and have all of the results combined. The final result set is awaitable, allowing the system to not block while waiting for all of the selectors to complete.</p>
  
  <pre><code>public async Task&lt;T&gt; GetBulkAsync&lt;T&gt;(Func&lt;IGetter, Task&lt;T&gt;&gt; selector) where T : IEnumerable&lt;T&gt;
  {
      Task&lt;T&gt;[] tasks = new Task&lt;T&gt;[this.getters.Count];
      for (int i = 0; i &lt; this.getters.Count; i++)
      {
          tasks[i] = selector(this.getters[i]);
      }
  
      T[] results = await Task.WhenAll(tasks);
  
      return results.SelectMany&lt;T, T&gt;(r =&gt; r);
  }
  </code></pre>
  
  <p>However, a problem comes up in my design here. There is one case where I simply want to use a selector that retrieves a single <code>IData</code> and then there's times where a selector will retrieve an <code>IEnumerable&lt;IData&gt;</code> or maybe a <code>List&lt;IData&gt;</code> or something entirely different.</p>
  
  <p>I have thought about using reflection to handle special cases with generic collections, but that's messy and requires additional work for every type of collection I want to handle.</p>
  
  <p>The main reason I care about <code>IEnumerable&lt;IData&gt;</code> (or really, <code>IEnumerable&lt;T&gt;</code>) is because I want to use Linq's SelectMany in order to flatten out all of the results in the big result set. If each selector is coming back with an <code>IEnumerable&lt;T&gt;</code>, it needs to be reduced into one <code>IEnumerable&lt;T&gt;</code>, not an <code>IEnumerable&lt;IEnumerable&lt;T&gt;&gt;</code>.</p>
  
  <p>Is there a good approach to solving this issue other than writing several different generic methods with constraints on collection types and without using reflection?</p>