0

SQL Server 2008 で c# を使用しています。データベースから多数の日付を読み取りたいプロジェクトを作成しています。これらの日付は、1 つずつ 1 つの列に格納されます。そして、取得したデータをリストに追加する必要があります。

私のコードは次のようなものです:

public List<DateTime> getholidays()
{
    DataTable table = new DataTable("holidays");

    SqlCommand command = new SqlCommand();
    command.Connection = conn;
    command.CommandType = System.Data.CommandType.Text;
    command.CommandText = "select holiday from holidays";

    //conn.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(command);
    adapter.Fill(table);

    List<DateTime> list=new List<DateTime>();

    foreach (DataRow row in table.Rows)
    {
        DateTime dt = new DateTime();
        dt = Convert.ToDateTime(row["holiday"]);
        list.Add(dt);
    }

    conn.Close();
    return list;
}
4

2 に答える 2

2

クロージャとグッドプラクティスの普及のために、DataTableは新しいオブジェクトであるため、入力する前にクリアする必要はありません。実際、DataReaderを使用する場合は、DataTableもまったく必要ありません。これが私があなたのコードを実装する方法です:

List<DateTime> dates = new List<DateTime>();

using(SqlCommand cmd = new SqlCommand("SELECT holiday FROM holidays1", conn))
using(SqlDataReader rdr = cmd.ExecuteReader()) {

    while( rdr.Read() ) {

        dates.Add( rdr.GetDateTime(0) );
    }
}

return dates;

より短く、よりシンプルに、より速く。

于 2013-01-22T20:24:27.557 に答える
0

私は私の問題の解決策を得ました.みんなに感謝します. これが私の新しいコードです

DataTable dt = new DataTable();
        List<DateTime> list = new List<DateTime>();

        SqlCommand cmd = new SqlCommand("select holiday from holidays1", conn);
        SqlDataAdapter da;
        da = new SqlDataAdapter(cmd);
        dt.Clear();
        da.Fill(dt);
        for (int i = 0; i < dt.Rows.Count - 1; i++)
        {
            list.Add(Convert.ToDateTime(dt.Rows[i][0]));
        }
        return list;
于 2013-01-22T07:48:20.943 に答える