这就是我目前从数据库中选择数据的方式:
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)
我怎样才能做到这一点?
谢谢!
如果要使用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)
| 归档时间: |
|
| 查看次数: |
8699 次 |
| 最近记录: |