Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit a foreach loop n runs?

Tags:

c#

datatable

Assuming I have the following loop:

foreach (DataRow dr in table.rows)
{
    ...
}

How do I keep it from running more often than n times?

like image 930
trojan man Avatar asked Oct 10 '11 17:10

trojan man


People also ask

How do you skip iterations in foreach?

Use return When you return , you skip the rest of the forEach() callback and JavaScript goes on to the next iteration of the loop. // Prints "2, 4" [1, 2, 3, 4, 5]. forEach(v => { if (v % 2 !== 0) { return; } console.

Is foreach loop infinite?

You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .


5 Answers

In case rows is actually just from DataTable.Rows, the simple Take answers given won't work as DataRowCollection only implements the non-generic IEnumerable interface, whereas LINQ needs the generic one. You'll need something like:

// Uses DataTableExtensions.AsEnumerable
foreach (DataRow dr in table.AsEnumerable().Take(50))

or

// Uses Enumerable.Cast
foreach (DataRow dr in rows.Cast<DataRow>().Take(50))
like image 120
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet


You could try

using System.Linq;
...
...
...
foreach (DataRow dr in rows.Cast<DataRow>().Take(50)) { }

Note that you have to call Cast<DataRow>() in order to convert DataRowCollection to IEnumerable<DataRow>, which will allow you to use the Take() extension method.

like image 40
Adam Ralph Avatar answered Oct 05 '22 23:10

Adam Ralph


Option 1: Have a running counter:

var i = 0;
foreach (DataRow dr in rows)
{
    i++;
    if(i >= 50) break;
}

Option 2: Use a for-loop

for(int i = 0; i <= 50; i++) {
    // This might actually crash if there are fewer than 50 rows
    var row = rows[i]; 
}
like image 37
Michael Stum Avatar answered Oct 05 '22 23:10

Michael Stum


Try this:

foreach (DataRow dr in table.Rows.Cast<DataRow>().Take(50))
{
    //your logic
}
like image 32
James Johnson Avatar answered Oct 05 '22 22:10

James Johnson


Ideally, modify your original query to only return 50 rows. There's no point in fetching more than you want to use.

Others have provided good alternatives if this is not an option.

like image 28
tenfour Avatar answered Oct 05 '22 22:10

tenfour