The order of the sequence passed is absolutely critical with TakeWhile , which will end as soon as the predicate returns false , while Where will continue to evaluate the sequence outside the first false .
A common use for TakeWhile is a lazy evaluation of large, expensive, or even infinite enumerated objects, where you may have additional knowledge about ordering a sequence.
eg. Given the sequence:
IEnumerable<BigInteger> InfiniteSequence() { BigInteger sequence = 0; while (true) { yield return sequence++; } }
A .Where will lead to an infinite loop trying to evaluate part of the enumerated:
var result = InfiniteSequence() .Where(n => n < 100) .Count();
While a .TakeWhile and armed with the knowledge that enumerated objects are ascending, will allow to evaluate the partial sequence:
var result = InfiniteSequence() .TakeWhile(n => n < 100) .Count();
StuartLC Jun 21 '14 at 11:04 2014-06-21 11:04
source share