How to limit foreach loop cycle?

Assuming I have the following loop:

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

How do I make it work more than n times?

+7
source share
6 answers

In case the rows are actually only from DataTable.Rows , simple Take answers will not work as the DataRowCollection implements the non-general IEnumerable interface, whereas LINQ needs a common one. You will 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)) 
+18
source

You can try

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

Note that you must call Cast<DataRow>() to convert the DataRowCollection to IEnumerable<DataRow> , which allows you to use the Take() extension method.

+9
source

Option 1: have a work counter:

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

Option 2: use for loop

 for(int i = 0; i <= 50; i++) { // This might actually crash if there are fewer than 50 rows var row = rows[i]; } 
+3
source

Ideally, modify the original query to return only 50 rows. It makes no sense to extract more than you want to use.

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

+3
source

Try the following:

 foreach (DataRow dr in table.Rows.Cast<DataRow>().Take(50)) { //your logic } 
+1
source

The .Cast<DataRow>().Take(50) Linq approaches are good, but this is a really simple problem for the for loop:

 for( int i = 0; i < Math.Min(50, rows.Count); ++i ) { var row = rows[i]; } 
0
source

All Articles