Skip to main content
edited tags
Link
Mathieu Guindon
  • 75.1k
  • 18
  • 191
  • 463
Tweeted twitter.com/#!/StackCodeReview/status/385740359630077952
Source Link
mbursill
  • 233
  • 1
  • 2
  • 4

Filtering a collection by an async result

I'm trying to do something like this:

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

The "IsYappyAsync" property would return a Task<bool>.

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

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

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

    var predicateResults = await Task.WhenAll<bool>(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?