Home > Enterprise >  IQueryable async loop
IQueryable async loop

Time:07-05

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

CodePudding user response:

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

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

CodePudding user response:

You should not await the calls to ToListAsync() Directly. fire off the all your queries and then await the results.

UPDATE - Missed the subtlety of the chained where for query2

// base query
var query = db.Table1.Where(t => t.age >= 18);

// execute the base query but do not await the result.
var res1 = query.ToListAsync();

// execute a second query adding an additional filter but do not await the result
var res2 = query.Where(t => t.dept == 1234).ToListAsync();

// process the results of the base query.
foreach (var item in await res1)
{
   ...
}

// process the results of the second query.
foreach (var item in await res2)
{
     ...
} 

There are a couple of mistakes in your code too (Now fixed in the question)

  • query.Where(t => t.dept = 1234); should probably be query.Where(t => t.dept == 1234); - Note double equals for equality check rather than a single one for assignment (I'd bet this is a typo though)
  • foreach (var item in query2) should probably be foreach (var item in res2) - there's not much point calling ToListAsync() and ignoring the result.
  • Related