【发布时间】:2019-08-07 10:17:37
【问题描述】:
是否有与以下等效的 LINQ?
static T Compose<T>(T source,
IEnumerable<Func<T, T>> funcs,
Func<T, bool> cond)
{
foreach (var func in funcs)
{
source = func(source);
if (cond(source)) break;
}
return source;
}
// This ends the composition as soon as a null is returned
var result = Compose(x, funcs, x => x == null);
本质上,我希望在彼此之上组合函数,如果当前值匹配特定条件则中断。
result = f(g(h(x))) // if condition is met somewhere within this chain,
// it will immediately break and return
编辑:我想到了一些类似的东西
funcs.Aggregate(seed, (x, f) => cond(x) ? x : f(x));
但这看起来令人困惑,并且最终会枚举整个集合,而不是在满足条件时中断。
【问题讨论】:
-
要在不满足条件后停止计算,您可以聚合函数本身,而不是其执行结果:
funcs.Aggregate((cur, next) => (i => { var val = cur(i); return cond(val) ? next(val) : val; }))