The following code:
public IEnumerable<AccountStructModel> Query(string query)
{
List<AccountStructModel> output = new List<AccountStructModel>();
using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int x = 0; x < reader.FieldCount; x++)
{
output.Add(new AccountStructModel { Username = reader[1].ToString(), Password = reader[2].ToString() });
}
}
command.Dispose();
}
connection.Close();
connection.Dispose();
}
return output;
}
Gives the following output:
Username | Password
---------|---------
Tim | randomPassword
The problem starts here:
new AccountStructModel { Username = reader[1].ToString(), Password = reader[2].ToString() }
I don't seem to be able to find a way to implement a loop that would take care of the following: reader[i]
instead of reader[1]
, reader[2]
, reader[3]
, reader[4]
, maybe the answer is obvious but I don't seem to be able to find it that easily.