如何选择数据到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 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
在你身边IDataReader
以实现你的结果是不值得的。
如果要使用DataRowCollection
填充自定义对象列表,可以使用LINQ和对象初始值设定项:
var lst = table.AsEnumerable().Select(r => new MyObject { FirstProperty = r.Field("FirstProperty"), OtherProperty = r.Field("OtherProperty") }).ToList();
试试这个代码。
public List 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 list=new List (); foreach(DataRow row in table) { MyClass instance = new MyClass(); instance.ID = row["ID"]; //similarly for rest of the properties list.Add(instance); } } return list; }
如果您使用的是ADO.NET方法 – 您将获得一个数据表,您可以将其转换为List或IEnumberable。
或者,您可以查看像nHibernate这样的ORM工具或使用LINQ to SQL