Let’s say you have a function that returns list of entities with logs. One entity may have 0 or more logs.
This code is likely slow, since you call LogRepository on each entity. In most situation (depends on your data profile), it is faster to get entire records with one call, and filter locally.
If you have many entity records, this is still slow, especially on allLogs.Where(x => x.EntityId == entity.Id) area. It is because you are going through entire logs for every entity.
We can make this faster by introducing new LINQ extension method IndexBy(). This is how you would use:
Source code for IndexBy():
You can use IndexBy() for any combination of properties.