I want to get a difference between TakeWhile & Where LINQ methods .I got the following data from MSDN .But It didn\'t make sense to me
Where
The order of the sequence passed is absolutely critical with TakeWhile
, which will terminate as soon as a predicate returns false
, whereas Where
will continue to evaluate the sequence beyond the first false
value.
A common usage for TakeWhile
is during the lazy evaluation of large, expensive, or even infinite enumerables where you may have additional knowledge about the ordering of the sequence.
e.g. Given the sequence:
IEnumerable InfiniteSequence()
{
BigInteger sequence = 0;
while (true)
{
yield return sequence++;
}
}
A .Where
will result in an infinite loop trying to evaluate part of the enumerable:
var result = InfiniteSequence()
.Where(n => n < 100)
.Count();
Whereas a .TakeWhile
, and armed with the knowledge that the enumerables is ascending, will allow the partial sequence to be evaluated:
var result = InfiniteSequence()
.TakeWhile(n => n < 100)
.Count();