Linq Example 43 - Aggregate Seed

11:46 PM
Linq Query:

//Aggregate Seed

            double startBalance = 100.0;

            int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

            double endBalance =
                attemptedWithdrawals.Aggregate(startBalance, (Curbalance, nextWithdrawal) =>
                        ((nextWithdrawal <= Curbalance) ? (Curbalance - nextWithdrawal) : Curbalance));

            Console.WriteLine("Ending balance: {0}", endBalance);

//
Output: 
Ending balance: 20

Explanation:


This one is quite Tricky.

We start From startBalance which is 100.

Next we try to attempt to withdraw some amount from this 100. Our attemp amount is in attemptedWithdrawals array.

First We attempt to Withdraw 20 . As ( 20 < 100 ) is true we Approve the Withdraw and now Our Balance is 100-20 = 80.

Next We attempt to Withdraw 10 . As ( 10 < 80 ) is true we Approve the Withdraw and now Our Balance is 80-10 = 70.

Next We attempt to Withdraw 40 . As ( 40 < 70 ) is true we Approve the Withdraw and now Our Balance is 70-40 = 30.

Next We attempt to Withdraw 50 . As ( 50 is not less than 30 ) we wont Approve the Withdraw and now Our Balance is same as before = 30.

Next We attempt to Withdraw 10 . As ( 10 < 30 ) is true we Approve the Withdraw and now Our Balance is 30-10 = 20.

Next We attempt to Withdraw 70 . As ( 70 is not less than 20 ) we wont Approve the Withdraw and now Our Balance is same as before = 20.

Next We attempt to Withdraw 30 . As ( 30 is not less than 20 ) we wont Approve the Withdraw and now Our Balance is same as before = 20.

So the Final Balance is 20 stored in endBalance.

0 comments:

Post a Comment