tags:

views:

2541

answers:

5

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  A: 
int count = 0;
foreach (ListViewItem lvi in listView.Items)
{
    if(++count > 50) break;
}
Chris Missal
A: 

This should work.

int i = 1;
foreach (ListViewItem lvi in listView.Items) {
    ...
    if(++i == 50) break;
}
Quintin Robinson
+21  A: 
int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   ++processed;
   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];
}
Hamish Smith
+1 for LINQ approach
Arnis L.
The ListViewItemCollection does not have an implementaion of Take() defined. Your example above won't compile.You could probably do something like theListView.Items.Cast<ListViewItem>().Take(50) but I think that a simple for loop would be much more performent.
Tim Jarvis
Watch out, listView might not contain 50 items! use `for(int i = 0; i < 50 i++)`
Ruben
ListViewItemCollection doesn't implement IEnumerable<T>, can't use LINQ
Marc
Enumerable.Cast<T> fixes that up : The Cast<(Of <(TResult>)>)(IEnumerable) method enables the standard query operators to be invoked on non-generic collections by supplying the necessary type information. For example, ArrayList does not implement IEnumerable<(Of <(T>)>) , but by calling Cast<(Of <(TResult>)>)(IEnumerable) on the ArrayList object, the standard query operators can then be used to query the sequence.
Steve Gilham
@Ruben: fixed it.
Martinho Fernandes
@Steven/Tim -- Thanks for the info, my own fault for not refreshing before posting a comment.
Marc
+3  A: 

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

Eric J.
+11  A: 

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.

sgriffinusa
if (listView.Items.Count < 50) throw new OutOfRangeException();
Armin