【发布时间】:2023-03-02 22:23:02
【问题描述】:
我正在使用 LINQ to 对象并有一个函数,在某些情况下,我需要在调用 Aggregate(...) 之前修改基础集合,然后在函数返回 Aggregate(...) 的结果之前将其返回到其原始状态。我当前的代码如下所示:
bool collectionModified = false;
if(collectionNeedsModification)
{
modifyCollection();
collectionModified = true;
}
var aggregationResult = from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue;
if(collectionModified)
modifyCollection();
return aggregationResult;
但是,正如所写,如果我修改集合,我会得到错误的结果,因为我在枚举 aggregationResult 之前将集合恢复到其原始状态,并且对 LINQ 结果进行延迟评估。我目前的解决方案是在我的 LINQ 查询中使用 .ToArray(),如下所示:
var aggregationResult = (from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue).ToArray();
结果数组的大小总是很小(
【问题讨论】: