# Calculate Total of Items in List

I would like to convert the following procedure to use Linq, but I'm not sure how to accomplish it, ForEach or Sum?

    public int GetBalance()
{
int balance = 0;

foreach (IDenomination denomination in Account)
{
balance += denomination.Currency * denomination.BillCount;
}

return balance;
}


Account is a property in the class:

public List<IDenomination> Account { get; set; }


Or you could do it in two steps, like you do it now. First calculate for each denomination and then sum:

int balance = Account.Select(denom => denom.Currency * denom.BillCount).Sum();

• Another awesome answer, thank you! I'm still somewhat of a noob with Linq so I really appreciate the help! – TrevorBrooks Feb 20 '15 at 17:44
• btw. Free upside of doing things this way: Linq's Sum() does overflow detection for you. Downside of doing things this way: its probably a little bit slower than your original foreach. (and of course the major upside is that reads better) – Hirle Feb 20 '15 at 17:59
• Agreed, it's definitely a bit of a trade off. – TrevorBrooks Feb 20 '15 at 18:01
• @Hirle You can actually do the lambda inside the Sum: var balance = Account.Sum(denom => denom.Currency * denom.BillCount); – Dan Lyons Feb 20 '15 at 18:58
• Cool, didnt know that! – Hirle Feb 20 '15 at 19:40

You could use the Aggregate extension method:

int balance = Account.Aggregate(0, (old, item) => old + item.Currency * item.BillCount);