LINQ, simplifying expression - take while sum of taken does not exceed given value

前端 未结 5 1215
别那么骄傲
别那么骄傲 2021-01-04 03:50

Given a setup like this ..

class Product {
   int Cost;
   // other properties unimportant
}

var products = new List {
    new Product { Cost         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 04:22

    Use a captured variable to track the amount taken so far.

    int sum = 0;
    
    IEnumerable query = products.TakeWhile(p =>
    {
      bool canAfford = (sum + p.Cost) <= credit;
      sum = canAfford ? sum + p.Cost : sum;
      return canAfford;
    });
    

提交回复
热议问题