Troy Bryant
Troy Bryant

Reputation: 1024

Foreach loop correctly

I have a data table and i'm trying to loop through the rows and create a zipCode array. This issue that i'm only getting one number 4 times. I know I'm doin something wrong but can somebody point this out to me and give and explanation.

Thanks

    public string bindMap()
{

    using (dal.Sys.RegionTableAdapters.region_countyListTa ta = new Cea.WebApp.JobsEq.Dal.Sys.RegionTableAdapters.region_countyListTa())
    {
        List<string> code = new List<string>();

        dal.Sys.Region.region_countyListDataTable dt = ta.GetData(region.RegionType, region.RegionCode);
        foreach (var row in dt)
        {                
            code.Add(region.ZipCode);                

        }//end foreach loop

        string codes = string.Join(",", code.ToArray());
        return codes.ToString();


    }//end for each loop        
}//end bind map

Upvotes: 0

Views: 124

Answers (2)

Davor Sagner
Davor Sagner

Reputation: 25

As a general desc of the row/cell value, I use this general (NOTE: GENERAL) block:

foreach(var item : items) {
//before adding there is maybe some casting or other work...
    listName.add(item["FieldName"]);
}

Understandable is that the listName is of type fieldNameType

Upvotes: 0

Bill Gregg
Bill Gregg

Reputation: 7147

You aren't using the variable that you are iterating with.

   foreach (var row in dt)
    {                
        //Not sure how you will get ZipCode from the ROW, but you get the idea. 
        code.Add(row["ZipCode"]);                

    }//end foreach loop

Upvotes: 6

Related Questions