我有一个IEnumerable值,我需要在开始时跳过某些元素,我正在使用SkipWhile它.但是,我肯定需要至少一个元素(假设序列甚至包含至少一个元素开头).如果所有元素都传递谓词(即跳过所有元素),我只想获得最后一个元素.如果没有昂贵的技巧,这种方式是否可行
items.SkipWhile(/* my condition */).FallbackIfEmpty(items.Last())
Run Code Online (Sandbox Code Playgroud)
(昂贵如下:它需要迭代序列两次,我想防止这种情况)
LINQ没有为此提供内置方法,但您可以编写自己的扩展.
在大多数情况下,此实现从Microsoft的参考代码中解除:
public static IEnumerable<TSource> SkipWhileOrLast<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
) {
bool yielding = false;
TSource last = default(TSource);
bool lastIsAssigned = false;
foreach (TSource element in source) {
if (!yielding && !predicate(element)) {
yielding = true;
}
if (yielding) {
yield return element;
}
lastIsAssigned = true;
last = element;
}
if (!yielding && lastIsAssigned) {
yield return last;
}
}
Run Code Online (Sandbox Code Playgroud)