c# – 如何选择数据到List而不是DataTable?

前端之家收集整理的这篇文章主要介绍了c# – 如何选择数据到List而不是DataTable?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这就是我目前从数据库中选择数据的方式:
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,我想选择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];
}

我怎样才能做到这一点?

谢谢!

解决方法

如果您不想深入了解LINQ to sql或Entity Framework,我建议您使用 dapper-dot-net.在大多数情况下,使用IDataReader在你身边摸索以实现你的结果是不值得的.

猜你在找的C#相关文章