how can we iterate datarow array in foreach loop

5.2k views Asked by At

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?

3

There are 3 answers

4
David Pilkington On

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.

0
Thorsten Dittmar On

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"];
0
Mohit S On

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.