How to filter a list asynchronously using LINQ?

Asked

Viewed 429 times

6

Example of code without the use of async:

var products = db.Products.Where(_ => _.UserId == currentUserId);

How do I make this asynchronous query taking into account that the Where of Linq does not support the use of await?

2 answers

6

The method Where builds an object that represents a query to be executed, and no query has been executed yet. That’s why does not make sense that the method Where is executed asynchronously.

What you must be looking for is the asynchronous execution of the method that actually executes the query. It is said that these methods materialize the query. An example is the method ToList, that transforms the object representing the query into a list of materialized objects.

The method ToList has a version that can be called asynchronously: ToListAsync, that allows the use of the keyword async what will make the materialization of the objects asynchronously.

// criando objeto que representa uma query, mas que não executa a mesma
var productsQuery = db.Products.Where(_ => _.UserId == currentUserId);

// materializando a query, ou seja, obtendo os resultados, de forma assíncrona
var products = await productsQuery.ToListAsync();

For additional information, it is also possible to do this when saving the data. The method SaveChanges also has an asynchronous alter-ego SaveChangesAsync:

// salvando as alterações feitas no context
db.SaveChangesAsync();
  • @Fernando: I added examples as you suggested.

4


The trick is to make up the list:

var products = await db.Products.Where(_ => _.UserId == currentUserId).ToListAsync();

See all asynchronous methods by this link here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.