如果A
是一個無限生成器,那麼在使用僅內置LINQ方法的單個語句中無法做到這一點。
要做到這一點,在一個聲明中,沒有任何副作用,您可能需要使用某種Scan
方法來計算輸入序列的prefix sum。那麼你只需要大於N
的第一個元素。簡單!
int sum = A().Scan((s, x) => s + x).First(s => s > N);
// ...
public static class EnumerableExtensions
{
public static IEnumerable<T> Scan<T>(
this IEnumerable<T> source, Func<T, T, T> func)
{
if (source == null) throw new ArgumentNullException("source");
if (func == null) throw new ArgumentNullException("func");
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
T accumulator = e.Current;
yield return accumulator;
while (e.MoveNext())
{
accumulator = func(accumulator, e.Current);
yield return accumulator;
}
}
}
}
}
您是指單個方法調用還是單個語句? – SLaks 2011-05-17 23:04:54
你的意思是'''? – SLaks 2011-05-17 23:06:31
@SLaks正確:) – 2011-05-17 23:14:26