rulururu

post Short precious code snippet

August 12th, 2009

Filed under: .NET — Kai @ 12:45 am

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
}

1 Comment »

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

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)