Short precious code snippet
August 12th, 2009
I was recently talking about linq features with a friend. Now I saw somebody wanted to break a loop after 50 iterations. Trivial but also for that there’s a precious solution using linq.
int processed = 0; foreach(ListViewItem lvi in listView.Items) { //do stuff ++processed; if (processed == 50) break; }
use linq
foreach(ListViewItem lvi in listView.Items.Take(50)) { //do stuff }
or, you’re right “old” style would be
for(int i=0; i < listView.Items.Count && i <= 50; i++) { ListViewItem lvi = listView.Items[i]; //do stuff }






the last loop will execute 51 times. it’s i<50, not i<=50, since you are starting at 0.
Comment by STEVEN SEAGAL — June 1, 2010 @ 7:31 am