请查看 Linqpad 中的以下代码并告诉我为什么它返回 0 项而不是 1 项。
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);
}
上面的代码没有像我预期的那样在 linqpad 中返回 1 个项目。相反,它返回 0 个项目。包含 1 个项目“banana”的列表应该返回。为什么不呢?
最佳答案
TakeWhile
的文档:
Returns elements from a sequence as long as a specified condition is true.
由于 List
是有序的,因此第一项“apple”不等于“banana”。条件为假,TakeWhile
在到达“banana”项之前退出。
您可能希望改用 Where
方法
Filters a sequence of values based on a predicate.
关于C# Linq List<string> takewhile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31881719/