C# LINQ对象聚合

C# LINQ对象聚合,c#,performance,linq,aggregation,C#,Performance,Linq,Aggregation,我经常将这段代码视为在c#中聚合对象枚举的一个示例: 这一个迭代了我的集合两次,这也是一个很大的浪费,特别是如果在我的对象上有更多的字段要聚合的话 我想我可以这样做: MyCoolObject aggregatedObject = myObjects.Aggregate(new MyCoolObject(), (accumlator, next) => { accumlator.Value1 += next.Value1; accumlator.Value2 += nex

我经常将这段代码视为在c#中聚合对象枚举的一个示例:

这一个迭代了我的集合两次,这也是一个很大的浪费,特别是如果在我的对象上有更多的字段要聚合的话

我想我可以这样做:

MyCoolObject aggregatedObject = myObjects.Aggregate(new MyCoolObject(), (accumlator, next) =>
{ 
    accumlator.Value1 += next.Value1;
    accumlator.Value2 += next.Value2;
    return accumlator;
};
这个函数创建一个accumlator对象,处理它,并在完成时返回它。对我来说,这看起来与手动Frach循环性能相当。
我很惊讶,我没有经常看到这种解决方案。这个解决方案会带来什么问题,可以解释这个问题吗?

通常的用法是修改累加器,然后返回累加器,而不是创建新对象。在本例中,我希望看到以下代码:

var aggregatedObject = myObjects.Aggregate(new MyCoolObject(),
    (accumulator, next) => {
       accumulator.Value1 +=next.Value1;
       accumulator.Value2 +=next.Value2;
       return accumulator;
    });

只有在修改累加器有副作用时,从累加器函数返回新对象才有意义。一个好的累加器对象不应该产生副作用。在这种情况下,最好使用不同的对象类型作为累加器。

1)您发布的示例并不常见。2) 代码还为每个输入行创建一个临时对象。是打字错误吗?3) 通常的用法是将当前值添加到累加器中并返回accumulator@PanagiotisKanavos我怀疑他建议的代码中的对象创建只是一个输入错误。除此之外,我同意你的看法事实上,新对象的创建是一个打字错误。永远不要复制粘贴你的坏榜样。
MyCoolObject aggregatedObject = myObjects.Aggregate(new MyCoolObject(), (accumlator, next) =>
{ 
    accumlator.Value1 += next.Value1;
    accumlator.Value2 += next.Value2;
    return accumlator;
};
var aggregatedObject = myObjects.Aggregate(new MyCoolObject(),
    (accumulator, next) => {
       accumulator.Value1 +=next.Value1;
       accumulator.Value2 +=next.Value2;
       return accumulator;
    });