0 votes
by (2.5k points)

I am trying to run an async method in a LINQ where statement. The simplest example would be something like this : 

var myList = Enumerable.Range(1, 100);
var filteredList = myList.Where(async x => CheckId(x));

async Task<bool> CheckId(int id)
{
    return true;
}

But when I try and compile this, I get this error : 

Cannot convert async lambda expression to delegate type 'Func<int, bool>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Func<int, bool>'.   

I get the error on the arrow function of the Where statement, but I'm not sure why. 

1 Answer

0 votes
by (2.5k points)

The error actually gives you a clue. Specifically, it's trying to tell you that the Where statement expects to input an integer (Which you are), and then output a boolean (Which at first glance, it may seem like you are). But in reality, async methods *must* return a Task or Task<T>. 

That's what the second part of the error is actually telling you when it says : 

An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Func<int, bool>'.   

That's the compiler saying "Hey, I know that you have started an async method here, and I know that an async method can *only* return void, Task or Task<T>, and so I know right away this is not going to work because I'm expecting a plain bool that is not wrapped in a task back". 

So how can you get around it? 

The simplest way is to simply move your Where statement to a bigger loop. Something like : 

var myList = Enumerable.Range(1, 100);
var filteredList = new List<int>();
foreach(var item in myList)
{
    if (await CheckId(item))
        filteredList.Add(item);
}

Another way is to add the System.Linq.Async package (https://www.nuget.org/packages/System.Linq.Async/). This allows you to do something like : 

var myList = Enumerable.Range(1, 100);
var filteredList = myList
                    .ToAsyncEnumerable()
                    .WhereAsync(async x => CheckId(x));

 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...