User
User

Reputation: 1662

how can we iterate datarow array in foreach loop

In dr i select the 102 rows from datatable.

Now i need to loop the first 100 dr values.I use the following for each loop its shows error like " cannot convert type datarow to int)

First i can take the 100 rows and process some logic after that logic i need to remove from the first 100 values from dr.after that i need to pick up the remaining 2 values.

DataRow[] dr = dtSourceDetail.Select("fld_description = '"+desc+"' ");
foreach(int i in dr.Take(100))
{
  //process some logic

  //here need to remove the first row from dr.  
}

How can i do this?

Upvotes: 0

Views: 5696

Answers (3)

Mohit S
Mohit S

Reputation: 14064

This might do the trick for you.

DataRow[] dr = dtSourceDetail.Select("fld_description = '"+desc+"' ");
for (int i = 0; i < dr.count; i=i+100)
{
    foreach(DataRow i in dr.Skip(i).Take(100))
    {
        //process some logic
    }
}

First loop that is simple for loop is just the counter for us. Then next foreach loop we are taking dr.Skip(i).Take(100) that means it will take 100 for the first time next time it skips 100 and gives you next 100. Since you dont have 100 records it will give you the rest records.

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

Well, Take returns an enumerable of DataRow objects. Not an enumerable of ints. So the loop variable must be a DataRow:

DataRow[] dr = dtSourceDetail.Select("fld_description = '"+desc+"' ");
foreach(DataRow row in dr.Take(100))
{
}

Now that you have a single row you can access the column values of that row as usual.

int i = (int)row["some_int_column"];

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13618

You need to change the type in the foreach to DataRow

DataRow[] dr = dtSourceDetail.Select("fld_description = '"+desc+"' ");
foreach(DataRow i in dr.Take(100))
{
  //process some logic

  //here need to remove the first row from dr.  
}

A foreach will try and cast each item that it receives from the enumerator to the type that you provide in the statement. In this case you provide int. It receives the first DataRow and then tries to cast it, which is where it is failing.

Upvotes: 1

Related Questions