Assuming I have the following loop:
foreach (DataRow dr in table.rows)
{
...
}
How do I keep it from running more often than n times?
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.
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 .
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))
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.
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];
}
Try this:
foreach (DataRow dr in table.Rows.Cast<DataRow>().Take(50))
{
//your logic
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With