【问题标题】:yield return slow database calls产量返回缓慢的数据库调用
【发布时间】:2012-11-01 09:03:33
【问题描述】:

在我的 ASP 项目中有这样的代码,用RegulationGroups 填充rr

private IEnumerable<RegulationGroup> LoadRegulations(string moduleName)  
{
    // database calls
    yield return subLrg;
}

在单独的类中,代码循环多次

foreach (RegulationGroup rg in rr.RegulationGroups)     
{

}

每次代码在RegulationGroups 上循环时,都会发生数据库调用。如何避免数据库调用?

我觉得可以

  1. 取消yield return 并使用List
  2. IEnumerable缓存在一个列表中并在我的模块中使用它,这样它就不会影响使用LoadRegulations方法的任何其他代码。

【问题讨论】:

  • 旁注:您的变量名称是 smwht shrtnd。请考虑在公共代码中使用可合理理解的名称(或明显是假的)。
  • 您也很可能不需要yield return 这些项目。 AsEnumerable 很有可能也能正常工作,而且效率会更高。

标签: c# asp.net yield-return


【解决方案1】:

您可以通过具体化查询来避免它,例如通过使用ToList():

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

这是由于deferred execution 的性质yield return

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

【讨论】:

  • 我在问题中没有看到任何提及 LINQ。 yield return 也使用延迟执行,但说它是由 LINQ 中的某些东西引起的是不准确的。
  • 是的,除了现在链接没有意义,因为它谈论的是 LINQ,而不是 yield return。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 2017-08-19
相关资源
最近更新 更多