VJOY
VJOY

Reputation: 3792

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

Upvotes: 1

Views: 2629

Answers (1)

kmp
kmp

Reputation: 10905

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
}

Upvotes: 1

Related Questions