自定义包容性TakeWhile(),还有更好的方法吗? [英] Custom Inclusive TakeWhile(), is there a better way?
问题描述
我编写了一个自定义LINQ扩展方法,该方法将TakeWhile()
方法扩展为包含的,而不是在谓词为false时将其扩展.
I've written a custom LINQ extension method that extends the TakeWhile()
method to be inclusive, rather than exclusive when the predicate is false.
public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool inclusive)
{
source.ThrowIfNull("source");
predicate.ThrowIfNull("predicate");
if (!inclusive)
return source.TakeWhile(predicate);
var totalCount = source.Count();
var count = source.TakeWhile(predicate).Count();
if (count == totalCount)
return source;
else
return source.Take(count + 1);
}
虽然可行,但我确信有更好的方法.我相当确定,就延迟执行/加载而言,这是行不通的.
While this works, I'm sure there is a better way of doing it. I'm fairly sure that this doesn't work in terms of deferred execution/loading.
ThrowIfNull()
是用于ArgumentNullException
检查的扩展方法
ThrowIfNull()
is a extension method for ArgumentNullException
checking
社区可以提供一些提示或重写吗? :)
Can the community provide some some hints or re-writes? :)
推荐答案
您是对的;这对推迟执行不友好(调用Count
需要对源进行完整枚举).
You are correct; this is not friendly to deferred execution (calling Count
requires a full enumeration of the source).
但是,您可以这样做:
public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate, bool inclusive)
{
foreach(T item in source)
{
if(predicate(item))
{
yield return item;
}
else
{
if(inclusive) yield return item;
yield break;
}
}
}
这篇关于自定义包容性TakeWhile(),还有更好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!