如何选择数据到List <T>而不是DataTable?

Wat*_*nce 6 c# c#-4.0

这就是我目前从数据库中选择数据的方式:

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;
}
Run Code Online (Sandbox Code Playgroud)

但它返回DataTable,我想选择List而不是DataTable.像这样:

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];
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

谢谢!

Jam*_*son 5

如果要使用DataRowCollection填充自定义对象列表,可以使用LINQ和对象初始值设定项:

var lst = table.AsEnumerable().Select(r =>
    new MyObject
    {
        FirstProperty = r.Field<int>("FirstProperty"),
        OtherProperty = r.Field<string>("OtherProperty")
    }).ToList(); 
Run Code Online (Sandbox Code Playgroud)


Mat*_*eid 4

如果您不想深入研究 LINQ to SQL 或实体框架,我建议您使用dapper-dot-net 。在大多数情况下,为了实现结果而摸索自己IDataReader是不值得的。