简体   繁体   English

list <>总和重载

[英]list<> sum overload

I have a class here that I want to sum(for every Traid T in list)(T.Price*T.Buy). 我在这里有一个要总结的类(列表中的每个Traid T)(T.Price * T.Buy)。 (Buy is +1 if it is a Buy, -1 one if a sell). (如果是“买入”,则买入为+1;如果是“卖出”,则买入为-1)。 So for instance if I have {Buy=-1,Price=10} and {Buy=1, price is =4} I would get -6. 例如,如果我有{Buy = -1,Price = 10}和{Buy = 1,price = 4},我将得到-6。 I want an eloquent way to do this, I am assuming I should do some kind of overloading? 我想以一种雄辩的方式做到这一点,我假设我应该进行某种重载? I'm new to programming and haven't done this before. 我是编程新手,之前从未做过。 Thanks in advance. 提前致谢。

-Rik -Rik

    private class Traid
        {
            public DateTime Date { get; set; }
            public int Index { get; set; }
            public int Buy { get; set; }
            public int Price {get;set;}
        }

您可以使用Enumerable.Sum

int total = list.Sum(t => t.Price*t.Buy);

Use Linqs Sum() Method on IEnumerable: 在IEnumerable上使用Linqs Sum()方法:

IEnumerable<Trade> trades = GetTrades();
var sum = trades.Sum(trade => trade.Buy * trade.Price);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM