Linq TakeWhile depending on the sum (or set) of elements

I have a list of items and you want to accept. If the sum (or any combination of elements) satisfies a certain condition. The following code does the job, but I'm sure this is not an unusual problem for which the correct template must exist.

var list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
int tmp = 0;
var listWithSum = from x in list
                  let sum = tmp+=x
                  select new {x, sum};
int MAX = 10;
var result = from x in listWithSum
             where x.sum < MAX
             select x.x;

Does anyone know how best to solve the problem, perhaps combining TakeWhile and Aggregate in one request?

thank

+5
source share
1 answer

, - Scan Reactive Extensions (System.Interactive part) - Aggregate, . :

var listWithSum = list.Scan(new { Value = 0, Sum = 0 },
         (current, next) => new { Value = next,
                                  Sum = current.Sum + next });

var result = listWithSum.TakeWhile(x => x.Sum < MaxTotal)
                        .Select(x => x.Value);

(MoreLINQ , btw - , .)

+2

All Articles