我有一个奇怪的错误,我不明白,并改变LINQ的IEnumerable列表中途固定它,我不明白为什么
不是真正的代码,但非常相似下面的代码不起作用:
// an IEnumerable of some object (Clasess) internally an array
var ansestors = GetAnsestors();
var current = GetCurrentServerNode();
var result = from serverNode in ansestors
select new PolicyResult
{
//Some irrelevant stuff
OnNotAvailableNode = NodeProcessingActionEnum.ContinueExecution,
};
var thisNode = new PolicyResult
{
//Some irrelevant stuff
OnNotAvailableNode = NodeProcessingActionEnum.ThrowException,
};
result = result.Reverse();
result = result.Concat(new List<PolicyResult> { thisNode });
result.First().OnNotAvailableNode = NodeProcessingActionEnum.ThrowException;
// When looking in the debugger, and in logs, the first element of the
// result sequence has OnNotAvailableNode set to ContinueExecution
// Which doesnt make any sense...
Run Code Online (Sandbox Code Playgroud)
但是,当我将结尾更改为以下内容时,它可以工作:
result = result.Reverse();
result = result.Concat(new List<PolicyResult> { thisNode });
var policyResults = result.ToList();
var firstPolicyResult = policyResults.First();
firstPolicyResult.OnNotAvailableNode = NodeProcessingActionEnum.ThrowException;
return policyResults;
Run Code Online (Sandbox Code Playgroud)
这里的所有类型都是类(引用类型),NodeProcessingActionEnum是一个枚举.
这是一个错误吗?
我错过了关于LINQ的一些重要事项?
救命?
result.First() 执行(延迟/延迟)查询.
该行将设置值OK,但是result稍后使用时,将再次执行查询.
稍后你会看到一个新获取的副本.事实上,它是不同的让我认为这GetAnsestors()也是懒惰的评估,而不是在内存中List<>
这意味着这ToList()是一个有价值的优化和修复.注意,在ToList之后你也可以使用
var firstPolicyResult = policyResults[0];
Run Code Online (Sandbox Code Playgroud)