0

I need to know how can I Stop foreach at it's last iteration. I don't know why but it's iterating once more than needed.

following is the code.

var rslista = result.Tables[0];
foreach (DataRow row in rslista.Rows)
{
}
samus
  • 6,102
  • 6
  • 31
  • 69
  • 1
    It will loop through for every row that is existing in your data table and not more. You may have blank row populated in your data table. I believe your issue is with your loading data into your data table or handling of null values inside your for each – techspider Sep 22 '16 at 16:44
  • I can't quite tell what data structure you're using since you have `var` instead of a explicit type, but you can check if the address of the last variable is equal to the current value of `row` and just `break` the loop. – Cody Sep 22 '16 at 16:46
  • you can try something like `foreach (DataRow row in rslista.Rows.Cast().Skip(rslista.Rows.Count - 1))` – Hackerman Sep 22 '16 at 16:49
  • So there's something not working as expected, and the *only conclusion* you can *possibly* reach is that the C# implementation of `foreach` *must* be broken? Good luck with that. – David Sep 22 '16 at 16:49
  • Duplicate (http://stackoverflow.com/questions/7476174/foreach-loop-determine-which-is-the-last-iteration-of-the-loop) answers question as asked, not that it is likely you are looking for something different - feel free to ask new question showing [MCVE] of the problem along with explanation what you are looking for. – Alexei Levenkov Sep 22 '16 at 17:16

1 Answers1

0

Set a breakpoint inside your foreach loop and take a look at the actual row that is being looped over which you feel shouldn't be there.

Sometimes there is a setting where a newrow object is preset in the datatable. One possible way to skip such a row is to check the rowstate or check for a null value in a column you expect data to be in. You can use the continue command to skip the row.

Don't copy and paste of of this code, but rather analyze what your data is and determine if one of the concepts below can help you.

DataTable dt = new DataTable();

foreach (DataRow dr in dt.Rows)
{
    if (dr.RowState == DataRowState.Added)
        continue;

    if (dr.RowState == DataRowState.Detached)
        continue;


}
Adam Heeg
  • 1,704
  • 1
  • 14
  • 34