简体   繁体   中英

Linq With TakeWhile in C#

What is best way to get list of best cards for example I want to get gift cards to apply for order total 100. It should return best combination like 30+40+75. below is my current code which stopped after 30+40 = 70 which is wrong because order total is more then 70 so we can not apply two gifts cards only. it should return 3 gift cards as shown above.

[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();
}

That's the usual behavior of TakeWhile , it returns elements from a sequence as long as a specified condition is true.

You have to tweak this a bit to include the next addition(which makes condition true).

    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();

Check this example

If I'm getting your question right, you are trying to select some subset of your giftcards such that sum of their balances is as close to orderTotal as possible, by still less or equal orderTotal . In the given case, the best option would be to just give to the user the 85-card, as no other combination seems better to me.

Sadly, this cannot be solved simply by straightforward use of LINQ. If this is not a NP-hard problem, try using some dynamic algorithm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM