当前位置: 首页 > 编程语言 > C#

如何选择数据到List而不是DataTable?分享

时间:2023-04-10 14:18:46 C#

如何选择数据到List而不是DataTable?这就是我目前从数据库中选择数据的方式:publicDataTableGetData(){DataTabletable=newDataTable("Table");使用(SqlConnectionconnection=newSqlConnection("Connectionstring")){SqlCommand命令=newSqlCommand();命令。连接=连接;command.CommandType=System.Data.CommandType.Text;command.CommandText="查询字符串";connection.Open();SqlDataAdapter适配器=newSqlDataAdapter(命令);适配器.填充(表格);}返回表;但它返回DataTable,我想选择List而不是DataTable。像这样:publicListGetData(){DataTabletable=newDataTable("Table");使用(SqlConnectionconnection=newSqlConnection("Connectionstring")){SqlCommand命令=newSqlCommand();命令。连接=连接;命令.CommandType=System.Data.CommandType.Text;command.CommandText="查询字符串";connection.Open();SqlDataAdapter适配器=newSqlDataAdapter(命令);适配器。填充(表格);}...返回[MyClass列表];}我怎样才能做到这一点?谢谢!如果你不想深入研究LINQtoSQL或EntityFramework,我建议你使用dapper-dot-net。在大多数情况下,不值得在您身边使用IDataReader来实现您的结果。如果要使用DataRowCollection填充自定义对象列表,可以使用LINQ和对象初始值设定项:varlst=table.AsEnumerable().Select(r=>newMyObject{FirstProperty=r.Field("FirstProperty"),OtherProperty=r.Field("OtherProperty")}).ToList();试试这段代码。publicListGetData(){DataTabletable=newDataTable("Table");使用(SqlConnectionconnection=newSqlConnection("Connectionstring")){SqlCommand命令=newSqlCommand();命令。连接=连接;command.CommandType=System.Data.CommandType.Text;command.CommandText="查询字符串";connection.Open();SqlDataAdapter适配器=newSqlDataAdapter(命令);适配器。填充(表格);列表列表=新列表();表中的行){MyClass实例=newMyClass();instance.ID=row["ID"];//对于其余的属性list.Add(instance)类似;}}返回列表;如果您使用的是ADO.NET方法-您将获得一个数据表,您可以将其转换为List或IEnumberable。或者,你可以看看nHibernate之类的ORM工具或者使用LINQtoSQL以上是C#学习教程:HowtoselectdataintoListinsteadofDataTable?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: