请查看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项。带有“香蕉”一项的列表应该返回。为什么不呢?
发布于 2015-08-08 15:43:23
只要条件为真,TakeWhile就会接受元素。在您的示例中,它在开始时是错误的,因为它是计算if ("apple" == "banana"),而不是TakeWhile停止。
如果你把“香蕉”这个元素放在开头,它就会起作用。
string[] strArray = {"banana", "apple", "cherry", "e"};另外,你只能写。
var lst2 = lst.TakeWhile(c=>c.Equals("banana"))选择是无用的。
发布于 2015-08-07 15:44:42
TakeWhile文档
返回序列中的元素,只要指定的条件为真。
由于List是有序的,第一项“苹果”不等于“香蕉”。条件为false,TakeWhile在到达“香蕉”项之前退出。
您可能希望使用Where方法来代替
根据谓词筛选值序列。
发布于 2015-08-07 15:46:55
@arcyqwerty解释了你为什么要得到结果。对于预期的结果,在本例中使用Where:
var lst2 = lst.Where(c=>c.Equals("banana"));而且,不需要Select(c => c),它是多余的。
https://stackoverflow.com/questions/31881719
复制相似问题