LINQ: query results cannot be listed more than once

This is my code.

searchDataContext db = new searchDataContext(); var query = (from p in db.SearchFirst(city, area) select new { ID = p.Id, Address = p.address, Level = p.agahilevel }); int count =query.Count(); // records var q = query.Skip(Convert.ToInt32(start)).Take(Convert.ToInt32(width)); if (q.Count() > 0) { int index = 0; str += "["; foreach (var row in q) { if (index == 0) 

I have an error in this code

 The query results cannot be enumerated more than once. 

please check this and answer me.

+4
source share
3 answers

Materialize the request:

 var addresses = (from p in db.SearchFirst(city, area) select new { ID = p.Id, Address = p.address, Level = p.agahilevel }) .Skip(Convert.ToInt32(start)) .Take(Convert.ToInt32(width)) .ToList(); 

Then use Enumerable.Any to check if it contains elements:

 if(addresses.Any()) { int index = 0; // ... } 
+8
source

You cannot use cached queries and iterate over them more than once ...
Make List<T> and try again

 var q = query.ToList(); // work on this 
+10
source

If you add .ToList() to your request, your problem will be solved.

+5
source

All Articles