目前我正在从数据库中选择数据:
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];
}
我该怎么做?
谢谢!
答案 0 :(得分:5)
如果要使用DataRowCollection
填充自定义对象列表,可以使用LINQ和对象初始值设定项:
var lst = table.AsEnumerable().Select(r =>
new MyObject
{
FirstProperty = r.Field<int>("FirstProperty"),
OtherProperty = r.Field<string>("OtherProperty")
}).ToList();
答案 1 :(得分:4)
如果您不想深入了解LINQ to SQL或Entity Framework,我建议您使用dapper-dot-net。在大多数情况下,使用IDataReader
让自己摸索以实现结果并不值得。
答案 2 :(得分: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;
}
答案 3 :(得分:1)
如果您正在使用ADO.NET方法 - 您将获得一个数据表,您可以将其转换为List或IEnumberable。
或者,您可以查看nHibernate之类的ORM工具或使用LINQ to SQL