【问题标题】:LINQ : The query results cannot be enumerated more than once [duplicate]LINQ:查询结果不能多​​次枚举[重复]
【发布时间】:2013-04-23 12:55:41
【问题描述】:

这是我的代码

 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)

这段代码有错误

The query results cannot be enumerated more than once.

请检查并回答我。

【问题讨论】:

标签: c# linq


【解决方案1】:

您不能使用缓存查询并对其进行多次迭代...
制作一个List<T> 然后再试一次

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

【讨论】:

    【解决方案2】:

    具体化您的查询:

    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();
    

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多