Rik
Rik

Reputation: 1987

list<> sum overload

I have a class here that I want to sum(for every Traid T in list)(T.Price*T.Buy). (Buy is +1 if it is a Buy, -1 one if a sell). So for instance if I have {Buy=-1,Price=10} and {Buy=1, price is =4} I would get -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

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

Upvotes: 2

Views: 181

Answers (2)

Mathias Becher
Mathias Becher

Reputation: 703

Use Linqs Sum() Method on IEnumerable:

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

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564433

You can use Enumerable.Sum:

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

Upvotes: 3

Related Questions