查询不能多次枚举

时间:2013-08-04 17:57:38

标签: linq c#-3.0

我想做以下

var totalNoOfRows = result.First().TotalNumberOfCount;

最后做那样的事情

bookssList.AddRange(retResult.Select(r => r.ToBook()));

其中ToBook是扩展方法

但我总是得到查询的结果不能多​​次枚举。

if (result != null)
                            {

    var totalNoOfRows = result.First().TotalNumberOfCount;
                                pagingContext.ItemsTotal = totalNoOfRows != null ? int.Parse(totalNoOfRows.ToString()) : 0;
                                var retResult = result.ToList();
                               // pagingContext.ItemsTotal = totalcount.Value != null ? int.Parse(totalcount.Value.ToString()) : 0;
                                                                    bookssList.AddRange(retResult.Select(r => r.ToBook()));
                            }

2 个答案:

答案 0 :(得分:2)

很难猜测你在做什么,以及这些片段如何相互关联,但如果你只能枚举一次,那么先调用ToArray

var resultCopy = result.ToArray();

//... any number of operations on resultCopy

请注意,调用First也算作枚举。因此,您需要在此之前枚举和复制集合。

答案 1 :(得分:0)

尝试将代码更改为此代码,因此您只需枚举result一次:

var retResult = result.ToList();
var totalNoOfRows = retResult.First().TotalNumberOfCount;  //You are now using LINQ on the list, not the query!
pagingContext.ItemsTotal = totalNoOfRows != null ? int.Parse(totalNoOfRows.ToString()) : 0;
                               // pagingContext.ItemsTotal = totalcount.Value != null ? int.Parse(totalcount.Value.ToString()) : 0;
Logger.LogInfo("Search Payments GetPaymentsWithCount stored procedure result not null and count=" + totalcount);
bookssList.AddRange(retResult.Select(r => r.ToBook()));