Linq Take,但取决于元素的总和(或总计) [英] Linq TakeWhile depending on sum (or aggregate) of elements
问题描述
我有一个元素列表,并希望在总和(或元素的任何集合)满足一定条件的同时进行.下面的代码可以完成这项工作,但是我很确定这不是一个应该存在适当模式的异常问题.
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;
有人知道如何更好地解决任务,可能将TakeWhile和Aggregate组合成一个查询吗?
Does somebody know how to solve the task in nicer way, probably combining TakeWhile and Aggregate into one query?
Thx
推荐答案
在我看来,您需要类似 Aggregate
,但产生的是序列而不是一个结果.然后,您可以这样做:
It seems to me that you want something like the Scan
method from Reactive Extensions (the System.Interactive part) - it's like Aggregate
, but yields a sequence instead of a single result. You could then do:
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 has a similar operator, btw - but currently it doesn't support the idea of the accumulator and input sequence not being the same type.)
这篇关于Linq Take,但取决于元素的总和(或总计)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!