IQueryable async loop

Here is a linq to sql query:

var query = db.Table1.Where(t => t.age >= 18); 
foreach (var item in query)
{
   ...
}

var query2 = query.Where(t => t.dept == 1234);
foreach (var item in query2)
{
     ...
} 

query and query2 are IQueryable objects. That means the sql queries are not executed until the foreach loop.

The previous code works fine. But i want to know how i can make this code async.

Here is what i’ve tried:

var query = db.Table1.Where(t => t.age >= 18); 
var res1 = await query.ToListAsync();
foreach (var item in res1)
{
   ...
}

var query2 = query.Where(t => t.dept = 1234);
var res2 = await query2.ToListAsync();
foreach (var item in res2)
{
     ...
} 

It works, but it is ugly to my eyes because i have to add 2 lines in my code.

So my question is: Is there a way to make the loop async ?

Something like that:

await foreach (var item in query2.ToListAsync())
{
   ...
}

Thanks

>Solution :

You can use the await keyword inside the foreach statement like so:

foreach (var item in await query2.ToListAsync())
{
   ...
}

Leave a Reply