Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
{
   ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading