我有一个代表业务数据的对象.
I've an object that represent a business data.
基本上,它是一个汇总一些总数的对象:
Basically, it's an object agregating some totals:
public class MyClass{
public double MyDataOne {get;set;}
public double MyDataTwo {get;set;}
public double MyDataThree {get;set;}
public static MyClass operator +(MyClass data1, MyClass data2){
return new MyClass{MyDataOne = data1.MyDataOne + data2.MyDataOne, MyDataTwo=data1.MyDataTwo+data2.MyDataTwo, MyDataThree=data1.MyDataThree+data2.MyDataThree };
}
}
现在,如果我有一个 IEnumerable<MyClass>myClasses
,有什么我可以在 MyClass 中实现的:?
Now, if I've an IEnumerable<MyClass> myClasses
, Is there somethings I can implement in MyClass to make this:?
myClasses.Sum(d=>d);
因为对我来说,添加对象的方式必须是对象而不是调用者的知识(如果有一天我多了一个数据,我不想查看我的整个代码来查看它的位置使用).
Because for me, the way an object is additioned must be the knowledge of the object and not the caller(if one day I've one data more, I don't want to look in my whole code to see where it is used).
谢谢
编写自己的扩展方法:
public static MyClass Sum(this IEnumerable<MyClass> source)
{
var result = new MyClass(); // all data will be zeros
foreach(var item in source)
result = result + item;
return result;
}
用法:
var sum = myClasses.Sum();
这篇关于对象上的Linq SUM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!