列表<>总和超载

时间:2012-11-17 01:49:03

标签: c# list generics overloading

我在这里有一个课我要总结(对于列表中的每个Traid T)(T.Price * T.Buy)。 (如果是买入,则买入为+1,如果卖出则为-1)。因此,例如,如果我有{Buy = -1,Price = 10}且{Buy = 1,price = 4},我会得到-6。我想要一个雄辩的方法来做到这一点,我假设我应该做一些超载?我是编程新手,之前没有这样做过。提前谢谢。

-Rik

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

2 个答案:

答案 0 :(得分:3)

您可以使用Enumerable.Sum

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

答案 1 :(得分:3)

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

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