Home > Mobile >  Correct way of using .ToLookup() with an EF Core query
Correct way of using .ToLookup() with an EF Core query

Time:01-10

I'm trying to use the .ToLookup() method with an EF Core query and wondering what the best practice is when using it, should I be buffering the query into a list first, or call .ToLookup() directly on the IQueryable?

var lookup = DbContext.Foo.Where(f => f.Id > 1).ToLookup(f => f.Id);

//vs:

var lookup = (await DbContext.Foo.Where(f => f.Id > 1).ToListAsync(cancellation)).ToLookup(f => f.Id);

My main concern is the ToListAsync approach will execute the query asynchronously whereas the direct .ToLookup call looks like it will block until results of the query are returned.

However as @Tim mentioned the ToListAsync approach will end up creating 2 collections in memory.

Thanks

CodePudding user response:

ToLookup creates an in-memory collection similar to a Dictionary<TKey, TValue>, so there is no need to create a list and then call ToLookup, you will just waste CPU and memory for no reason.

So it's similar to ToDictionary, but different to GroupBy. The latter is using "deferred execution", which means you are still in a database context when you consume it, whereas the lookup or dictionary are collections that are already filled.

  • Related