C # Linq List <string> takewhile

Please see the following code in Linqpad and tell me why it returns 0 items instead of 1 item.

void Main()
{
    string[] strArray = {"apple", "banana", "cherry", "e"};
    List<string> lst = strArray.ToList();

    //count all occurences of variable alphabet "e" in LINQ

    //tip is to get the occurences of letter "e" in each word
    // and then total them together

    var lst2 = lst.TakeWhile(c=>c.Equals("banana")).Select(c=>c);

    Console.WriteLine(lst2);
}

      

The above code does not return 1 item in linqpad as I expected. Instead, it returns 0 items. The list with 1 item "banana" should return. Why is it wrong?

+3


source to share


6 answers


The item TakeWhile

will accept the item as long as the condition is true. In your case, it's false at the start because it evaluates if ("apple" == "banana")

and it doesn't stop TakeWhile

.

If you put the banana element at the beginning, it will work.

string[] strArray = {"banana", "apple", "cherry", "e"};

      



Also, you can only write.

 var lst2 = lst.TakeWhile(c=>c.Equals("banana"))

      

The choice is useless.

+1


source


Documentation for TakeWhile

:

Returns elements from a sequence if the specified condition is true.

Since a is List

ordered, the first element "apple" is not equal to "banana". The condition is false and TakeWhile

ends before it reaches the banana point.



You can use the method instead Where

Filters a sequence of values ​​based on a predicate.

+11


source


@arcyqwerty explained why you are getting your results. For expected results, use Where

in this case:

var lst2 = lst.Where(c=>c.Equals("banana"));

      

Moreover, there is no need for it Select(c => c)

, it is redundant.

+3


source


Because it accepts when the iterated item is a banana, since the first item it hits is not a banana, it stops the iteration.

+2


source


This will return 1 item ("banana"):

var result = lst.Where(c => c.Equals("banana")).ToList();
Console.WriteLine(result);

      

As others have pointed out, there is no need for TakeWhile

where simple enough Where

.

EDIT: From your code comments, it looks like you are trying to count the occurrences of "e" in the original list. This will do it for you:

var list = new List<string> { "apple", "banana", "cherry", "e" };

var count = list
    .SelectMany(x => x.ToArray()) // flatten into list of chars
    .Where(x => x.Equals('e'))
    .Count();
Console.Write(count);

      

+1


source


arcyqwerty tell you why. Instead, it gave up on what you need:

var lst2 = lst.Where(c=>c.Equals("banana")).Select(c=>c);

      

0


source







All Articles