【发布时间】:2015-05-05 01:56:04
【问题描述】:
我在循环中使用了一个 takewhile 语句,它只在循环的第一次迭代中给出结果。所有后续迭代都没有产生结果,尽管我希望它们会产生结果。
例如下面的代码。第一次迭代将给出字符串 a="blah1blah2blah3"。在第二次迭代中,我期望 a="blah2blah3",但 takewhile 没有给出任何 a="",它没有得到任何元素。
在现实世界的场景中,这是一个很大的逻辑循环,所以我不能在循环之外执行 takewhile。我尝试使用 count() 和 take() 的组合,但是 count() 给出了所有符合条件的元素,而不是在条件为 false 之前符合条件的项目的计数。
任何帮助都会很有用,谢谢。
代码:
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()));
}
}
【问题讨论】:
-
对,因为它从头开始,而不是从您当前的元素开始。你想
skipWhile你还没有到达元素,然后才到达takeWhile,但是测量性能这在大集合上可能会很慢,一个简单的for循环也可以解决它。 -
在您展示的示例中,
a未被使用,并且可以在代码运行之前的某个时间点完全优化。您需要实际使用您的结果(例如,将其写入控制台或文本文件)以使结果具有任何意义。 -
@SébastienSevrin 为什么会有帮助?
-
你可以用
string.Concat代替string.Join。 -
如果
.name是编译时string则.name.ToString()没有意义。