3

The following code example works of course:

var ints = new List<int> { 1, 2, 3 };
var smallInts = ints.Where(i => i < 3);

But what if need to call an async method in a Where condition?

var ints = new List<int> { 1, 2, 3 };
var smallInts = ints.Where(async i => { return await IsSmallInt(i); });

This results in the following error:

Error 21: Cannot convert async lambda expression to delegate type 'System.Func'. An async lambda expression may return void, Task or Task, none of which are convertible to 'System.Func'.

Of course I could just write a foreach loop in this case, but I don't want to.

var smallInts = new List<int>();
foreach (int i in ints)
    if (await IsSmallInt(i))
        smallInts.Add(i);

So what's the best way (and maybe also the shortest way) to use await in a Where condition?

Michael Geier
  • 1,653
  • 1
  • 16
  • 18
  • Why do you want to make it asynchronous? Is there some IO-bound computation in your **IsSmallInt** method? If not, asynchronous programming will not be of any help and you should stick with the synchronous version. – Horizon_Net Jan 29 '15 at 12:22
  • 3
    [LINQ has very limited support for async/await](http://stackoverflow.com/a/16624843/859154) – Royi Namir Jan 29 '15 at 12:24
  • 1
    http://stackoverflow.com/questions/21868087/how-to-await-a-list-of-tasks-asynchronously-using-linq http://stackoverflow.com/questions/252355/how-to-write-asynchronous-linq-query http://stackoverflow.com/questions/18176722/how-to-write-async-linq Google: what a beautiful little thing ... – Darek Jan 29 '15 at 12:29
  • You can write your WhereAsync quite simple, sadly i can not post it anymore: Select a anonymous class containing a the Task predicate and the value. Await all. and selet the values again. – quadroid Jan 29 '15 at 12:36

0 Answers0