I don't like these mutation approaches inside linq queries.
EDIT: I did not claim that my previous code was untested and was somewhat pseudo-y. I also missed the fact that the Unit actually eats the whole thing at once - as correctly pointed out that this did not work. However, the idea was right, but we need an alternative to Aggreage.
It is a shame that LINQ does not have a working unit. I suggest code from user2088029 in this post: How to calculate the current amount of an int series in a Linq query? .
And then use this (which is verified and what I intended):
var y = people.Scanl(new { item = (Person) null, Amount = 0 }, (sofar, next) => new { item = next, Amount = sofar.Amount + next.Amount } );
Stolen code for longevity:
public static IEnumerable<TResult> Scanl<T, TResult>( this IEnumerable<T> source, TResult first, Func<TResult, T, TResult> combine) { using (IEnumerator<T> data = source.GetEnumerator()) { yield return first; while (data.MoveNext()) { first = combine(first, data.Current); yield return first; } } }
Previous, wrong code:
I have another suggestion; start with a list
people [{"a", 100}, {"b", 200}, ... ]
Calculate current totals:
people.Aggregate((sofar, next) => new {item = next, total = sofar.total + next.value}) [{item: {"a", 100}, total: 100}, {item: {"b", 200}, total: 300}, ... ]
Then use TakeWhile and Select to return to just the elements;
people .Aggregate((sofar, next) => new {item = next, total = sofar.total + next.value}) .TakeWhile(x=>x.total<1000) .Select(x=>x.Item)