Search code examples
asp.netwhile-loopforeachdatatable

Need to go true While () and foreach()


Im trying to go true a foreach if a value is less or equal to a number. I have a while before but it only runs 1 time and then foreach But need the while to be checked everytime How can i get that to happen

This is my code that i have tried for now:

While (i <= batchSize)
{

foreach (DataRow dtRow in dt1.Rows) 
{
                        var number = dtRow.ItemArray[0];
                        var surname = dtRow.ItemArray[1];
                        var forename = dtRow.ItemArray[2];
                        var emailAddress = dtRow.ItemArray[3];
                        string taxidentifier = (string)dtRow.ItemArray[4];
                        //string taxidentifier = "2211221143";

                        if (Personnummer.Valid(taxidentifier))
                        {

                            body += "{\"itemId\": \"" + number + "\",\"subjectId\": \"" + taxidentifier + "\"},";
                            batch = i++;

                        }
}

Solution

  • The while statement condition needs to be checked at every iteration of the foreach statement ?

    Since the while runs only one time, just replace the while statement to an if one with the same condition at the beginning of the foreach :

    foreach (DataRow dtRow in dt1.Rows) {
        if (i > batchSize)
            break;
        // Do what you have to;
    }