C# LINQ:查询结果不能枚举多次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16169920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:14:26  来源:igfitidea点击:

LINQ : The query results cannot be enumerated more than once

c#linq

提问by 8611670474

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.

请检查并回答我。

采纳答案by Tim Schmelter

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.Anyto check if it contains elements:

然后用于Enumerable.Any检查它是否包含元素:

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

回答by bash.d

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

您不能使用缓存查询并多次迭代它们...
制作并重List<T>

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

回答by Maryam Arshi

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

如果您添加.ToList()到查询中,您的问题将得到解决