7

これは現在、データベースからデータを選択している方法です:

public DataTable GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    return table;
}

しかし、それは DataTable を返すので、DataTable の代わりに List を選択したいと思います。このような:

public List<MyClass> GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    ...
    return [List of MyClass];
}

これどうやってするの?

ありがとう!

4

4 に答える 4

6

を使用しDataRowCollectionてカスタムオブジェクトのリストを作成する場合は、LINQとオブジェクト初期化子を使用できます。

var lst = table.AsEnumerable().Select(r =>
    new MyObject
    {
        FirstProperty = r.Field<int>("FirstProperty"),
        OtherProperty = r.Field<string>("OtherProperty")
    }).ToList(); 
于 2012-05-08T20:25:47.200 に答える
4

LINQ to SQL または Entity Framework を掘り下げたくない場合は、dapper-dot-netを使用することをお勧めします。ほとんどの場合、結果を具体化するために自分自身を手探りIDataReaderすることは、努力する価値がありません。

于 2012-05-08T20:14:23.707 に答える
3

このコードを試してください。

public List<MyClass> GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";
        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
        List<MyClass> list=new List<MyClass>();
        foreach(DataRow row in table)
        {
            MyClass instance = new MyClass();
            instance.ID = row["ID"];
            //similarly for rest of the properties

            list.Add(instance);
        }

    }

    return list;
}
于 2012-05-08T20:14:31.320 に答える
1

ADO.NET アプローチを使用している場合は、データ テーブルが返され、それを List または IEnumberable に変換できます。

または、nHibernate などの ORM ツールを調べたり、LINQ to SQL を使用したりすることもできます

于 2012-05-08T20:13:11.557 に答える