日期:2014-05-20  浏览次数:20737 次

LINQ小问题
C# code

 public void Linq93()
{
    double startBalance = 100.0;
 
    int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
 
    double endBalance =
        attemptedWithdrawals.Aggregate(startBalance,
            (balance, nextWithdrawal) =>
                ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
 
    Console.WriteLine("Ending balance: {0}", endBalance);
}


求解释。

------解决方案--------------------
Aggregate,累计。

原来有100元,不断扣钱,但是如果不够扣了,就不扣了。
------解决方案--------------------
Aggregate 用法,将结果 与下一个元素 进行操作,你的是 三元运算。
大致如下
C# code

            /*
             (100,20)=> 100-20=80
             (80,10) => 80-10=70
             (70,40) => 70-40=30
             (30,50) => 30
             (30,10) => 30-10=20
             (20,70) => 20,
             (20,30) => 20
             */

------解决方案--------------------