Alex Rivera | Logout

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

Asked 2011-09-13T13:07:42.303
18

Given a setup like this ..

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

var products = new List<Product> {
    new Product { Cost = 5 },
    new Product { Cost = 10 },
    new Product { Cost = 15 },
    new Product { Cost = 20 }
};

var credit = 15;

Assume that the list will be sorted in the given order. I wish to basically iterate over each item in the list, keep a summed value of cost, and keep getting products out as long as the total cost does not exceed credit.

I can do this with some loops and stuff, but I was wondering if there is a way to compact it into a simpler LINQ query.

Edit
Report

1 Answer

16

Not "fully" linq, because it needs one extra variable, but it is the easiest I could think of:

int current=0;
var selection = products.TakeWhile(p => (current = current + p.Cost) <= credit);
answered 2011-09-13T13:12:26.353

Your Answer