首页 > 解决方案 > 类初始化循环

问题描述

以下代码:

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],也许答案是显而易见的,但我似乎无法那么容易地找到它。

标签: c#loops

解决方案


推荐阅读