LINQ where vs takewhile

后端 未结 6 1307
感情败类
感情败类 2021-01-30 07:46

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

        
6条回答
  •  悲哀的现实
    2021-01-30 08:33

    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();
    

提交回复
热议问题