[英]Linq TakeWhile in loop, giving only first result
I'm using a takewhile statement in a loop and its only giving results on the first iteration of the loop. 我在循环中使用了takewhile语句,它仅在循环的第一次迭代中给出结果。 All the subsequent iterations are not producing results, even though I would expect them to.
所有后续迭代都不会产生结果,即使我希望它们能够产生结果。
For example the code below. 例如下面的代码。 The first iterations will give string a="blah1blah2blah3".
第一次迭代将给出字符串a =“ blah1blah2blah3”。 On the second iteration I would expect a="blah2blah3", but the takewhile is giving nothing a="", its getting no elements.
在第二次迭代中,我期望a =“ blah2blah3”,但是需要的时间却没有给出a =“”,它没有任何元素。
In the real world scenario this is a big loop of logic, so I can't afford to do the takewhile outside of the loop. 在现实世界中,这是一个很大的逻辑循环,因此我无法承担超出循环的时间。 I've tried to use a combination of count() and take(), but count() gives all the elements that qualify, not the count of items that qualify until the condition is false.
我试过使用count()和take()的组合,但是count()给出了所有符合条件的元素,而不是符合条件的项目计数,直到条件为假。
Any help would be useful, thanks. 任何帮助将是有用的,谢谢。
Code: 码:
public void blah()
{
List<testclass> someStrings = new List<testclass>()
{ new testclass() { name = "blah1", testNum = 1 },
new testclass() { name = "blah2", testNum = 2 },
new testclass() { name = "blah3", testNum = 3 },
new testclass() { name = "none4", testNum = 4 },
new testclass() { name = "blah5", testNum = 5 },
new testclass() { name = "blah6", testNum = 6 },
new testclass() { name = "none7", testNum = 7 }
};
foreach (testclass tc in someStrings)
{
string a = string.Join("", someStrings.TakeWhile(i => i.name.Contains("blah")
&& i.testNum >= tc.testNum).Select(g => g.name.ToString()));
}
}
I am not sure what you are trying to achieve from this but the problem with your code is, when you loop executes for second time ie for testNum
as 2
your query looks like this:- 我不确定您要从中实现什么,但是代码的问题是,当您第二次执行循环时,即对于
testNum
为2
您的查询如下所示:-
string a = someStrings.Where(i => i.name.Contains("blah")
&& i.testNum >= 2).Select(g => g.name.ToString());
So, Obviously the first condition itself will fail ie i.testNum >= 2
for first element which contains 1
and you will get nothing or String.Empty as output. 因此,显然第一个条件本身将失败,即,对于包含
1
第一个元素, i.testNum >= 2
,您将不会获得任何结果或String.Empty作为输出。
As far as what I have understood, you can achieve what you want by adding SkipWhile
before as suggested by @CodeDennis to skip previous records like this:- 据我了解,您可以按照@CodeDennis的建议添加之前的
SkipWhile
来跳过以前的记录,从而实现所需的目标:-
string a = string.Join("", someStrings.SkipWhile(i => i.testNum < tc.testNum)
.TakeWhile(i => i.name.Contains("blah") && i.testNum >= tc.testNum)
.Select(g => g.name.ToString()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.