如果我有一个foreach循环,有没有办法检查一个布尔值?
我不想在内部检查foreach()然后打破例如.我想要foreach收集一个集合,同时评估某些事情是否属实.
例如,我不想这样做:
IEnumerable<Job> jobs = currentJobs;
foreach(Job job in jobs)
{
if (found)
break;
}
Run Code Online (Sandbox Code Playgroud)
Sco*_*ock 19
尝试使用TakeWhile.
从示例:
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
banana
mango
*/
Run Code Online (Sandbox Code Playgroud)
Dav*_*iez 17
我找到了另一种方法:
foreach (var car in cars) if (!rentedCars.Contains(car))
{
// Magic
}
Run Code Online (Sandbox Code Playgroud)
Chu*_*ebs 15
你总是可以把它变成for循环.
for (i = 0; i < jobs.Count && booleanTrue; i++) {
// do a lot of great stuff
}
Run Code Online (Sandbox Code Playgroud)
您还需要将工作从更改IEnumerable为IList.我认为IList会更好地满足你的目的.IEnumerablelazy在您需要之前评估元素,并且不包括关联的集合助手方法.
Mar*_*ell 11
不是很喜欢它,但也许是一些LINQ?
bool yourBool = false;
foreach(var item in
collection.TakeWhile(x => yourBool))
{...}
Run Code Online (Sandbox Code Playgroud)
?
我能正确理解你吗?
我不明白使用foreach循环的阻力; 我会坚持你拥有或拥有的东西
foreach(var job in jobs.TakeWhile(x => someCondition(x)) {
someAction(job);
}
Run Code Online (Sandbox Code Playgroud)