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.
有帮助吗?

解决方案

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#?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top