自定义包含TakeWhile(),有更好的方法吗?

Ala*_*tts 5 c# linq refactoring

我编写了一个自定义LINQ扩展方法,该TakeWhile()方法将该方法扩展为包含,而不是在谓词为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);
        }
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我确信有更好的方法.我很确定这在延迟执行/加载方面不起作用.

ThrowIfNull()是一种ArgumentNullException检查的扩展方法

社区可以提供一些提示或重写吗?:)

Ada*_*son 14

You are correct; this is not friendly to deferred execution (calling Count requires a full enumeration of the source).

You could, however, do this:

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;
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)