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

前端 未结 5 1218
别那么骄傲
别那么骄傲 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:10

    ok, re my comment above in @Aducci's answer, here's a version using Scan

          var result=products.Scan(new {Product=(Product)null, RunningSum=0},
            (self, next) => new {Product=next, RunningSum=self.RunningSum+next.Cost})
            .Where(x=>x.RunningSum<=credit)
            .Select(x => x.Product);
    

    And this is my implementation of Scan (which I assume is similar to what's in the Rx Framework, but I haven't checked)

        public static IEnumerable Scan(this IEnumerable source,
          TAccumulate seed, Func accumulator) {
    
          foreach(var item in source) {
            seed=accumulator(seed, item);
            yield return seed;
          }
        }
    

提交回复
热议问题