Linq与C#中的TakeWhile

SOF*_*ser 1 c# linq entity-framework c#-4.0

什么是获得最佳卡列表的最佳方式,例如我想获得礼品卡申请订单总数100.它应该返回最佳组合,如30 + 40 + 75.下面是我当前的代码,30+40 = 70由于订单总数超过70 而停止了之后错误因此我们不能仅申请两张礼品卡.它应该返回3张礼品卡,如上所示.

[Test]
public void GetBestAvailableGiftCards()
{
    var list = new List<GiftCard>
    {
        new GiftCard() {CardNumber = "45964123358448514", SecurityCode = "032443", Balance = 75},
        new GiftCard() {CardNumber = "45964123345954414", SecurityCode = "032443", Balance = 85},
        new GiftCard() {CardNumber = "45964062845645735", SecurityCode = "435448", Balance = 40},
        new GiftCard() {CardNumber = "28872034245533173", SecurityCode = "934465", Balance = 30}
    };

    var orderTotal = 100;
    double current = 0;
    var cards = list
        .OrderBy(x => x.Balance)
        .TakeWhile(card => (current = current + card.Balance) <= orderTotal)
        .ToList();
}
Run Code Online (Sandbox Code Playgroud)

Har*_*sad 6

这是通常的行为TakeWhile,只要指定的条件为真,它就会返回序列中的元素.

您必须稍微调整一下以包含下一个添加(使条件成立).

    var orderTotal = 100;
    double current = 0;
    var cards = list
        .OrderBy(x => x.Balance)
        .TakeWhile(card => 
         {              
            bool returnvalue = current < orderTotal; 
            current += card.Balance;
            return returnvalue;
        })
        .ToList();
Run Code Online (Sandbox Code Playgroud)

检查一下 example

  • 它必须是`bool returnvalue = current <orderTotal;`不是`<=` (2认同)