简体   繁体   English

Linq与TakeWhile在C#中

[英]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. 什么是获得最佳卡列表的最佳方法,例如,我想获得礼品卡以申请总计100张订单。它应返回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. 下面是我当前的代码,该代码在30+40 = 70之后停止,这是错误的,因为订单总数超过70,所以我们不能仅应用两张礼品卡。 it should return 3 gift cards as shown above. 如上图所示,它应该返回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();
}

That's the usual behavior of TakeWhile , it returns elements from a sequence as long as a specified condition is true. 这是TakeWhile的通常行为,只要指定条件为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 检查这个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 . 如果我的问题是对的,则您尝试选择礼品卡的一些子集,以使它们的余额总和尽可能接近orderTotal ,但仍小于或等于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. 在给定的情况下,最好的选择是只给用户一张85张卡片,因为在我看来,没有其他组合可以比这更好。

Sadly, this cannot be solved simply by straightforward use of LINQ. 可悲的是,这不能简单地通过直接使用LINQ来解决。 If this is not a NP-hard problem, try using some dynamic algorithm. 如果这不是NP难题,请尝试使用一些动态算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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