[Solved] how to loop through collection and save to db [closed]


I don’t see an issue, but if you’re asking if your approach is improvable, yes.

I would simply use a class with these properties(inclusing gender).

class Person
{
    public bool IsFemale { get; set; }
    public string Name { get; set; }
}

Now you can create a single collection, for example a List<Person> and loop that.

var persons = new List<Person>() { 
    new Person{IsFemale=false, Name="john"},new Person{IsFemale=false, Name="james"},
    new Person{IsFemale=true, Name="stacy"},new Person{IsFemale=true, Name="paula"}
};

foreach(Person p in persons)
{
    //call to stored procedure there
    //parameters
    //execute
}

Edit: If you have problems with the ADO.NET part, here’s an example:

using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand("StoredProcedureName", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@Gender", typeof(string));
    cmd.Parameters.Add("@Name", typeof(string));
    con.Open();
    foreach (var person in persons)
    {
        cmd.Parameters["@Gender"].Value = person.IsFemale ? "female" : "male";
        cmd.Parameters["@Name"].Value = person.Name;
        cmd.ExecuteNonQuery();
    }
}

solved how to loop through collection and save to db [closed]