给定一个 Enumerable,我想要使用 Take() 方法获取到包括终止符在内的所有元素(如果没有找到终止符则抛出异常)。类似于下面的代码:
list.TakeWhile(v => !condition(v)).Concat(list.Single(condition))
除了糟糕的,我只想走一遍它。
使用.NET 4和Rx中当前的操作符是否能够简洁地实现此操作?还是需要编写新的操作符?
编写操作符所需时间比编写这个问题更少(尽管我认为其中一半的时间将用于想出如何命名此函数),但我不想重复已经存在的内容。
更新
好的,这里是操作符。非常激动人心,我知道。无论如何,有可能从内置操作符中构建它吗?
public static IEnumerable<T> TakeThroughTerminator<T>([NotNull] this IEnumerable<T> @this, Func<T, bool> isTerminatorTester)
{
foreach (var item in @this)
{
yield return item;
if (isTerminatorTester(item))
{
yield break;
}
}
throw new InvalidOperationException("Terminator not found in list");
}
Zip()
进行前瞻,但这仍然需要遍历枚举两次 - 使用运算符是正确的方法。 - BrokenGlass