lizardkingLK
lizardkingLK

Reputation: 41

Why is this method not giving the correct result for last element 'Strawberry'?

In this code snippet taken and I modified from microsoft learn. See below

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        IEnumerable<string> query = new string[]
        {
           "apple",
           "passionfruit",
           "banana",
           "mango",
           "orange",
           "blueberry",
           "grape",
           "strawberry"
        }.TakeWhile(delegate (string fruit, int index)
        {
           Console.WriteLine(@"
           fruit is {0}
           index is {1}
           length is {2}
           is length greater than or equal to index? {3}",
           fruit,
           index,
           fruit.Length,
           fruit.Length >= index);

           return fruit.Length >= index;
      });
    
      foreach(var fruit in query)
      {
      }
   }
}

from here it ignores the last element in the list which is "strawberry" for some unknown reason.

It should stdout

fruit is strawberry index is 7 length is 10 is length greater than or equal to index? True

As per my understanding the IEnumerable only executes when it gets called by an iterator. So that does not explain the issue.

Upvotes: -3

Views: 65

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37095

"fruit is strawberry index is 7 length is 10 is length greater than or equal to index? True" Yes, that's true. However "grape", which is checked before, because it has index 6, has a lenght of 5. TakeWhile will stop iterating as soon as it finds an element that doesn't satisfiy the condition, which is the case for "grape":

Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements."

Apart from this, this is a horrible use of TakeWhile. LINQ-queries, are queries, they should never produce side-effects like writing to console or whatever. These should probably go into your foreach.

Upvotes: 1

Related Questions