简体   繁体   中英

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. 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(); And I am getting error on ToList() itself.
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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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