1
\$\begingroup\$

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; }
\$\endgroup\$
10
\$\begingroup\$

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();
\$\endgroup\$
  • \$\begingroup\$ Another awesome answer, thank you! I'm still somewhat of a noob with Linq so I really appreciate the help! \$\endgroup\$ – TrevorBrooks Feb 20 '15 at 17:44
  • 1
    \$\begingroup\$ 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) \$\endgroup\$ – Hirle Feb 20 '15 at 17:59
  • \$\begingroup\$ Agreed, it's definitely a bit of a trade off. \$\endgroup\$ – TrevorBrooks Feb 20 '15 at 18:01
  • 7
    \$\begingroup\$ @Hirle You can actually do the lambda inside the Sum: var balance = Account.Sum(denom => denom.Currency * denom.BillCount); \$\endgroup\$ – Dan Lyons Feb 20 '15 at 18:58
  • \$\begingroup\$ Cool, didnt know that! \$\endgroup\$ – Hirle Feb 20 '15 at 19:40
6
\$\begingroup\$

You could use the Aggregate extension method:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.