简体   繁体   English

LINQ错误:不能多次枚举查询结果

[英]LINQ error : The query results cannot be enumerated more than once


I am working on a LINQ function in which I am using ToList() inside a for loop. 我正在使用LINQ函数,其中在for循环中使用ToList()。 At the 1st iteration it works fine but then onward it throws an exception as 在第一次迭代中,它工作正常,但随后又抛出异常,因为

"The query results cannot be enumerated more than once." “查询结果不能被多次枚举。”

The sample code is; 示例代码为;

for()
{
     functionCall();
}

functionCall()
{
   var query = <<query logic>>;
   query.ToList();
}

I searched a lot to fix this but everyone is saying use ToList(); 我进行了大量搜索以解决此问题,但所有人都说使用ToList(); And I am getting error on ToList() itself. 而且我在ToList()本身上遇到错误。
Please help me out to resolve this issue. 请帮助我解决此问题。


Thanks in advance 提前致谢

You are evaluating the query more than once, why not refactor your code to this..? 您不止一次评估查询,为什么不将代码重构为此呢?

// Evaluate the query once
var query = <<query logic>>.ToList();

// Do your loop, passing the evaluated results into the function
for()
{
    functionCall(query);
}

functionCall(query)
{
   //Do whatever you need here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM