列表<>总和重载



我这里有一个类,我想对它求和(对于列表中的每个Traid T)(T.Price*T.Buy)。(如果是买入,买入为 +1,如果是卖出,则为 -1)。 因此,例如,如果我有 {Buy=-1,Price=10} 和 {Buy=1,价格为 =4},我会得到 -6。 我想要一种雄辩的方式来做到这一点,我假设我应该做某种重载? 我是编程新手,以前没有这样做过。 提前谢谢。

-里克

    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);

在 IEnumerable 上使用 linqs sum() 方法:

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