int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
if(++count > 50) break;
}
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.
}
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.
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).
This should work.
int i = 1;
foreach (ListViewItem lvi in listView.Items) {
...
if(++i == 50) break;
}
Source: Stackoverflow.com