Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

foreach

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) 
like image 276
Jade M Avatar asked Aug 11 '09 22:08

Jade M


1 Answers

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]; } 
like image 116
Hamish Smith Avatar answered Oct 08 '22 23:10

Hamish Smith