LINQ:实现 TakeLastWhile 运算符





5.00/5 (1投票)
TakeLastWhile 运算符返回序列中满足指定条件的最后一个连续元素,并作为 TakeLastWhile 扩展方法实现。
在之前的文章之后(>)(>),在这篇文章中,我将介绍 TakeLastWhile
运算符的实现。
TakeLastWhile
运算符返回序列中满足指定条件的最后一个连续元素,并作为 TakeLastWhile
扩展方法实现。
public static IEnumerable<TSource> TakeLastWhile<TSource>
(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
public static IEnumerable<TSource> TakeLastWhile<TSource>
(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
此方法执行的操作更加简单。我们从一个空缓冲区开始,并将满足由谓词实现的条件的所有项目添加到缓冲区中。每当一个项目不满足条件时,缓冲区就会被清除。
var buffer = new List<TSource>();
foreach (var item in source)
{
if (predicate(item))
{
buffer.Add(item);
}
else
{
buffer.Clear();
}
}
遍历 source
序列后,我们只需将缓冲区中的所有项目(如果有的话)yield出去。
foreach (var item in buffer)
{
yield return item;
}
考虑项目索引的重载,仅在调用实现条件的谓词时有所不同。
var buffer = >new >List<TSource>();v
var idx = 0;
foreach (>var item >in source)
{
if (predicate(item, idx++))
{
buffer.Add(item);
}
>else
{
buffer.Clear();
}
}
foreach (var item in buffer)
{
yield return item;
}
您可以在 CodePlex 项目中找到此运算符(以及更多运算符)的完整实现,用于 LINQ 工具和运算符:PauloMorgado.Linq。