C# 在 X 个项目后跳出 foreach 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1263364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Break out of foreach loop after X number of items
提问by Jade M
In my foreach loop I would like to stop after 50 items, how would you break out of this foreach loop when I reach the 50th item?
在我的 foreach 循环中,我想在 50 个项目后停止,当我到达第 50 个项目时,你将如何打破这个 foreach 循环?
Thanks
谢谢
foreach (ListViewItem lvi in listView.Items)
采纳答案by Hamish Smith
int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
//do stuff
if (++processed == 50) break;
}
or use LINQ
或使用 LINQ
foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
//do stuff
}
or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)
或者只是使用常规的 for 循环(如@sgriffinusa 和 @Eric J 所建议的那样)
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
回答by Chris Missal
int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
if(++count > 50) break;
}
回答by Quintin Robinson
This should work.
这应该有效。
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
回答by Eric J.
Or just use a regular for loop instead of foreach. A for loop is slightly faster (though you won't notice the difference except in very time critical code).
或者只是使用常规的 for 循环而不是 foreach。for 循环稍微快一点(尽管除了非常时间关键的代码之外,您不会注意到差异)。
回答by sgriffinusa
Why not just use a regular for loop?
为什么不使用常规的 for 循环?
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
Updated to resolve bug pointed out by Ruben and Pragmatrix.
更新以解决 Ruben 和 Pragmatrix 指出的错误。
回答by Caique Romero
Just use break, like that:
只需使用break,就像这样:
int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
if(cont==50) { //if listViewItem reach 50 break out.
break;
}
cont++; //increment cont.
}