Question

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

  1. do away with yield return and use a List
  2. cache the IEnumerable in a list and use it in my module so that it doesn't affect any other code using the LoadRegulations method.
Was it helpful?

Solution

You can avoid it by materializing the query, f.e. by using ToList():

var regulations = LoadRegulations("moduleName").ToList();

It's due to the nature of deferred execution of the yield return.

What is the purpose/advantage of using yield return iterators in C#?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top