[英]C# Linq List<string> takewhile
Please look at following code in Linqpad and tell me why it returns 0 items instead of 1 items. 请查看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);
}
The above code does not return 1 item in linqpad as I would expect. 上面的代码没有像我期望的那样在linqpad中返回1个项目。 Instead it returns 0 items. 相反,它返回0项。 The list with 1 item "banana" should return. 带有1个项目“banana”的列表应该返回。 Why does it not? 为什么不呢?
Documentation for TakeWhile
: TakeWhile
文档:
Returns elements from a sequence as long as a specified condition is true. 只要指定的条件为真,就返回序列中的元素。
Since a List
is ordered, the first item, "apple" does not equal "banana". 由于订购了List
,因此第一项“apple”不等于“banana”。 The condition is false and TakeWhile
exits before it reaches the "banana" item. 条件为false, TakeWhile
在到达“banana”项目之前退出。
You may be looking to use the Where
method instead 您可能希望使用Where
方法
Filters a sequence of values based on a predicate. 根据谓词过滤一系列值。
@arcyqwerty explained why you're getting your results. @arcyqwerty解释了为什么你得到你的结果。 For your expected results, use Where
in this instance: 对于您的预期结果,请在此实例中使用Where
:
var lst2 = lst.Where(c=>c.Equals("banana"));
Also, no need for Select(c => c)
, it's redundant. 此外,不需要Select(c => c)
,这是多余的。
只因它走,而迭代项目是香蕉,因为第一个项目它到达不是香蕉,停止迭代。
This will return 1 item ("banana"): 这将返回1项(“香蕉”):
var result = lst.Where(c => c.Equals("banana")).ToList();
Console.WriteLine(result);
As the others pointed out, no need for a TakeWhile
where a simple Where
will suffice. 正如其他人所指出的那样,没有必要使用TakeWhile
,其中一个简单的Where
就足够了。
EDIT: From your code comments, it looks like you might be trying to count the occurrences of 'e' in the source list. 编辑:从您的代码注释,看起来您可能正在尝试计算源列表中出现的'e'。 This will do that 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);
The TakeWhile
will take element as long as the condition is true. 只要条件为真, TakeWhile
将采用元素。 In your case it's false at the beginning because it's evaluate if ("apple" == "banana")
and it's not so the TakeWhile
stop. 在你的情况下,它在开始时是假的,因为它评估if ("apple" == "banana")
并且不是TakeWhile
停止。
If you put the element "banana" at beginning, it will work. 如果你把元素“banana”放在开头,它就会起作用。
string[] strArray = {"banana", "apple", "cherry", "e"};
Plus, you can only write. 另外,你只能写。
var lst2 = lst.TakeWhile(c=>c.Equals("banana"))
The select is useless. 选择没用。
arcyqwerty tell you why. arcyqwerty告诉你为什么。 He left out what you want instead: 他遗漏了你想要的东西:
var lst2 = lst.Where(c=>c.Equals("banana")).Select(c=>c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.