I'm gathering a list of users and their information that I would like to store in a database table. I have this database set up in Microsoft SQL Server Management Studio. The primary key of the database is set to auto-incrementing. I need the loop to end when there are no more users in the list. I have two valid users in the test account however what I currently have only inserts a single user. Would I be better off to use a sqlDataAdapter?
List<User> result = ims.ListUsers(req).ListUsersResult.Users;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);
for (int i = 1; i < result.Count(); i++)
{
foreach (User user in result.Where(x => x.UserName.Contains('@')))
{
string sql = @"INSERT INTO UserInfo (UserID, UserName) VALUES (@UserID, @UserName)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@UserID", i);
command.Parameters.AddWithValue("@UserName", user.UserName);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
forloop. It seems that theforeachis doing everything you need.