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?
source to share
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.
source to share
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.
source to share
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);
source to share