In my ASP project there is code like this, to populate rr with RegulationGroups
private IEnumerable<RegulationGroup> LoadRegulations(string moduleName)
{
// database calls
yield return subLrg;
}
In a separate class, the code loops over multiple times
foreach (RegulationGroup rg in rr.RegulationGroups)
{
}
Each time the code loops over RegulationGroups the database call occurs. How can I avoid the database calls?
I think I can
- do away with
yield returnand use aList - cache the
IEnumerablein a list and use it in my module so that it doesn’t affect any other code using theLoadRegulationsmethod.
You can avoid it by materializing the query, f.e. by using
ToList():It’s due to the nature of
deferred executionof theyield return.What is the purpose/advantage of using yield return iterators in C#?