Следующий код:
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;
}
Дает следующий вывод:
Username | Password
---------|---------
Tim | randomPassword
Проблема начинается здесь:
new AccountStructModel { Username = reader[1].ToString(), Password = reader[2].ToString() }
Кажется, я не могу найти способ реализовать цикл, который бы позаботился о следующем: reader[i]
вместо reader[1]
, reader[2]
, reader[3]
, reader[4]
, возможно, ответ очевиден, но мне кажется, я не могу найти его так легко.