Filtering a collection by an async result I'm trying to do something like this:

var loudDogs = dogs.Where(async d =&gt; await d.IsYappyAsync);


The "IsYappyAsync" property would return a Task&lt;bool&gt;.

Obviously this isn't supported, so instead I've built an extension method called WhereAsync.

public static async Task&lt;IEnumerable&lt;T&gt;&gt; WhereAsync&lt;T&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, Task&lt;bool&gt;&gt; predicate)
{
    var results = new List&lt;T&gt;();
    var tasks = new List&lt;Task&lt;bool&gt;&gt;();

    foreach (var item in items)
    {
        var task = predicate.Invoke(item);
        tasks.Add(task);
    }

    var predicateResults = await Task.WhenAll&lt;bool&gt;(tasks);

    var counter = 0;
    foreach (var item in items)
    {
        var predicateResult = predicateResults.ElementAt(counter);

        if (predicateResult)
            results.Add(item);

        counter++;
    }

    return results.AsEnumerable();
}


This probably isn't the best approach, but I'm at a loss for something better. Any thoughts?
There are several ways to achieve what you're after and it depends on whether you want the results drip fed to you as they're available or whether you're happy to have them all in one bang.
The way you've implemented your method gives it all in one bang - which is fine.

A shorter implementation could be

public static async Task&lt;IEnumerable&lt;T&gt;&gt; WhereAsync2&lt;T&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, Task&lt;bool&gt;&gt; predicate)
{
    var itemTaskList = items.Select(item=&gt; new {Item = item, PredTask = predicate.Invoke(item)}).ToList();
    await Task.WhenAll(itemTaskList.Select(x=&gt;x.PredTask));
    return itemTaskList.Where(x=&gt;x.PredTask.Result).Select(x=&gt;x.Item);
}



It builds a list of an anonymous type where the type contains the item and the Task.
It then waits for all of the tasks to complete.
It then goes through that list from (1) and picks out the items that had a true result from the Task.


The other advantage is that you get rid of all of that counter and ElementAt() stuff.  Either way still builds a complete List for the items in the given Enumerable...  

Aside: You could investigate something like Rx if you wanted the results via an IObservable&lt;T&gt; instead.  The result wouldn't even be async Task - it would just be an IObservable.