我有一个我不明白的奇怪错误,并将 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...
但是当我将结局更改为以下内容时,它会起作用:
result = result.Reverse();
result = result.Concat(new List<PolicyResult> { thisNode });
var policyResults = result.ToList();
var firstPolicyResult = policyResults.First();
firstPolicyResult.OnNotAvailableNode = NodeProcessingActionEnum.ThrowException;
return policyResults;
这里的所有类型都是类(引用类型),除了 NodeProcessingActionEnum 是一个枚举。
这是一个错误吗?
我错过了有关 LINQ 的一些重要内容吗?
帮忙?
最佳答案
result.First()
执行(延迟/延迟)查询。
该行将设置值 OK,但是当您使用 result
时稍后查询将再次执行。。
稍后您将看到新获取的副本。事实上,它是不同的,让我假设 GetAnsestors()
也是惰性评估的,并且不在内存中 List<>
这意味着 ToList()
是一个有值(value)的优化和修复。请注意,在 ToList 之后,您还可以使用
var firstPolicyResult = policyResults[0];
关于c# - .Net 的 LINQ 中存在错误,或者我遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9820623/