Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 that and answer me.

like image 959
8611670474 Avatar asked Apr 23 '13 12:04

8611670474


3 Answers

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

var q = query.ToList(); // work on this
like image 62
bash.d Avatar answered Oct 22 '22 22:10

bash.d


Materialize your query:

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; // ...
}
like image 23
Tim Schmelter Avatar answered Oct 22 '22 21:10

Tim Schmelter


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

like image 26
Maryam Arshi Avatar answered Oct 22 '22 21:10

Maryam Arshi