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()
is a extension method for ArgumentNullException
checking
Can the community provide some some hints or re-writes? :)