Custom Inclusive TakeWhile (), is there a better way?

I wrote a special LINQ extension method that extends the method TakeWhile()so that it is included, and not 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 am sure there is a better way to do this. I am sure this does not work in terms of deferred execution / loading.

ThrowIfNull()is an extension method for ArgumentNullExceptionchecking

Can the community provide some clues or rewrite? :)

+3
source share
2 answers

You're right; this does not apply to deferred execution ( Counta full source numbering is required for a call ).

You could, however, do the following:

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;
        }
    }
} 
+12

. , SkipWhile TakeWhile.

IEnumerable<string> list = new List<string> { "1", "2", "3", "4", "5" };
var result = list
    .Reverse()
    .SkipWhile(item => item != "3")
    .Reverse();
// result will be {"1", "2", "3"}

, , , , list . , .

0

Source: https://habr.com/ru/post/1751318/


All Articles