Linq TakeWhile depending on sum (or aggregate) of elements
Posted
by martinweser
on Stack Overflow
See other posts from Stack Overflow
or by martinweser
Published on 2010-04-23T13:53:22Z
Indexed on
2010/04/23
14:03 UTC
Read the original article
Hit count: 195
I have a list of elements and want to takeWhile the sum (or any aggregation of the elements) satisfy a certain condition. The following code does the job, but i am pretty sure this is not an unusual problem for which a proper pattern should 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 somebody know how to solve the task in nicer way, probably combining TakeWhile and Aggregate into one query?
Thx
© Stack Overflow or respective owner