本文介紹了對象上的Linq SUM?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我有一個代表業務數據的對象.
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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!