开发者

How do I limit a foreach loop n runs?

Assuming开发者_如何转开发 I have the following loop:

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

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


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]; 
}


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.


Try this:

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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜