Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi all
i try to use foreach loop on a linq query but up this error:
"The query results cannot be enumerated more than once"
C#
string st = "Adel";
dbDidDataContext db = new dbDidDataContext();
var res = db.spJobmenu(st);
foreach (var item in res)
{
    Console.Write(item.name.ToString());
}

and it clear works on:
C#
string s = res.First().name.ToString();
Posted

1 solution

The result set cannot be queried. It is an ISingleResult<t> which works a bit differently to IQueriable and IEnumerable.

Try adding ToList(). This will make sure that the SP has returned the data before you start iterating through it:

C#
string st = "Adel";
dbDidDataContext db = new dbDidDataContext();
var res = db.spJobmenu(st).ToList();
foreach (var item in res)
{
    Console.Write(item.name.ToString());
}


the .First() method will also cause the results to be fetched, same as ToList. That is why the example you gave works

Hope that helps ^_^
Andy
 
Share this answer
 
Comments
mohamadMahmodi 13-Aug-15 11:30am    
hey Andy , i think you are my project angel!thank you, it works
Animesh Datta 14-Aug-15 1:03am    
5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900