C# Break out of foreach loop after X number of items

送分小仙女□ 提交于 2020-01-11 17:07:09

问题


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?

Thanks

foreach (ListViewItem lvi in listView.Items)

回答1:


int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   if (++processed == 50) break;
}

or use 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(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}



回答2:


Why not just use a regular for loop?

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.




回答3:


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).




回答4:


This should work.

int i = 1;
foreach (ListViewItem lvi in listView.Items) {
    ...
    if(++i == 50) break;
}



回答5:


int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
    if(++count > 50) break;
}



回答6:


Just use break, like that:

int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
   if(cont==50) { //if listViewItem reach 50 break out.
      break; 
   }
   cont++;   //increment cont.
}


来源:https://stackoverflow.com/questions/1263364/c-sharp-break-out-of-foreach-loop-after-x-number-of-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!