简体   繁体   English

查询的结果不能多​​次枚举

[英]The result of a query cannot be enumerated more than once

I had a question pertainning to Parelle and Task in this thread. 我在这个帖子中有一个关于Parelle和Task的问题。 Previous Question Related to this one 上一个问题与此相关

What I am attempting to do is iterate over a collection returned from the entity framework via a sproc. 我试图做的是通过sproc遍历从实体框架返回的集合。

Everything query's perfectly on the first loop but on the second when I try to skip past the previous query results I'm getting an The result of a query cannot be enumerated more than once error. 一切查询完全在第一个循环,但在第二个,当我尝试跳过前面的查询结果我得到一个查询的结果不能被多次枚举错误。

I realize the debugger is telling me that I cannot page this collection in this fashion. 我意识到调试器告诉我,我不能以这种方式分页这个集合。

How do I use .Skip() and not get that error? 我如何使用.Skip()并没有得到该错误? I need to be able to iterate over the entire collection until the end is reached. 我需要能够遍历整个集合,直到到达终点。

What's the magic to do this? 这样做的魔力是什么?

Like I mentioned I can loop once, but after that I get that error. 就像我提到的,我可以循环一次,但之后我得到了那个错误。

HELP! 救命!

ObjectResult<Guid?> memIDs = await Task.Run(() => db.proc_GetCollaborator_UserIDs(projectID));
if (memIDs != null)
{
    while (true)
    {
        var t = memIDs.Take(Environment.ProcessorCount)
                      .Select(id => Task.Run(() => projCollabors.Add(new Collaborator(id.Value, projectID))))
                      .Skip(skip)
                      .ToArray();
        if (t.Length == 0) { break; };
        skip += Environment.ProcessorCount;

        await Task.WhenAll(t);
    };
};

Your query memIDs.Take(Environment.ProcessorCount) always takes the first Environment.ProcessorCount items from memIDs . 您的查询memIDs.Take(Environment.ProcessorCount)始终从memIDs获取第一个Environment.ProcessorCount项。

It doesn't "remember" that you took a certain number of items the next time you call .Take on it - it will always start from the beginning again. 它不“记住”你花了一定数量的项目的下次呼叫时间.Take就可以了-它总是会再次从头开始。

Because you're calling it in a loop, memIDs is being repeatedly enumerated. 因为您在循环中调用它, memIDs重复枚举memIDs I'm thinking that's where the error is coming from. 我在想这就是错误的来源。

You could fix this by turning it into a list like so: 您可以通过将其转换为如下列表来解决此问题:

var memIDsList = memIDs.ToList();

And then use memIDsList instead of memIDs . 然后使用memIDsList而不是memIDs

However, that won't help with your faulty query logic. 但是,这对您的错误查询逻辑没有帮助。 I assume you're trying to take N items at a time and do something with them? 我假设你一次尝试N个项目并用它们做点什么?

If so, you could use MoreLinq's Batch extension. 如果是这样,您可以使用MoreLinq的 Batch扩展。 (See Create batches in linq for more info about Batch .) (有关Batch详细信息,请参阅在linq中创建批次 。)

I don't know if using Batch would avoid the need for .ToList() , but you should try it without. 我不知道使用Batch是否会避免使用.ToList() ,但你应该不用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM