如何将DataTable转换为类Object

我已经开发了一个应用程序,可以在任何地方返回DataTable。

现在我的客户端想要转换(使用服务堆栈使用某些部分),所以我需要在我的应用程序中返回DTO(对象)。

我不想更改现有的存储过程,甚至不想尽可能多地使用LINQ(我对LINQ并不太了解)。

对于小function,我可以使用Linq没问题。

我的问题是:如何将我的DataTable更改为该类的对象?

示例代码如下

 string s = DateTime.Now.ToString(); DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("name"); for (int i = 0; i < 5000000; i++) { DataRow dr = dt.NewRow(); dr["id"] = i.ToString(); dr["name"] = "name" + i.ToString(); dt.Rows.Add(dr); dt.AcceptChanges(); } List clslist = new List(); for (int i = 0; i < dt.Rows.Count; i++) { Class1 cls = new Class1(); cls.id = dt.Rows[i]["id"].ToString(); cls.name = dt.Rows[i]["name"].ToString(); clslist.Add(cls); } Response.Write(s); Response.Write("
"); Response.Write(DateTime.Now.ToString());

我知道,上面是耗时的,所以我试图找到一个替代解决方案。

有没有其他方法(我猜,LINQ to DataTable),通过它直接将表行转换为List

所以我可以在服务堆栈中返回对象并继续。

初始化DataTable:

 DataTable dt = new DataTable(); dt.Columns.Add("id", typeof(String)); dt.Columns.Add("name", typeof(String)); for (int i = 0; i < 5; i++) { string index = i.ToString(); dt.Rows.Add(new object[] { index, "name" + index }); } 

查询本身:

 IList items = dt.AsEnumerable().Select(row => new Class1 { id = row.Field("id"), name = row.Field("name") }).ToList(); 

阿米特,我用一种方法以更少的编码和更有效的方式实现这一目标。

但它使用Linq。

我在这里发布了它,因为答案可能有助于其他SO。

DAL代码下面将数据表对象转换为List of YourViewModel,这很容易理解。

 public static class DAL { public static string connectionString = ConfigurationManager.ConnectionStrings["YourWebConfigConnection"].ConnectionString; // function that creates a list of an object from the given data table public static List CreateListFromTable(DataTable tbl) where T : new() { // define return list List lst = new List(); // go through each row foreach (DataRow r in tbl.Rows) { // add to the list lst.Add(CreateItemFromRow(r)); } // return the list return lst; } // function that creates an object from the given data row public static T CreateItemFromRow(DataRow row) where T : new() { // create a new object T item = new T(); // set the item SetItemFromRow(item, row); // return return item; } public static void SetItemFromRow(T item, DataRow row) where T : new() { // go through each column foreach (DataColumn c in row.Table.Columns) { // find the property for the column PropertyInfo p = item.GetType().GetProperty(c.ColumnName); // if exists, set the value if (p != null && row[c] != DBNull.Value) { p.SetValue(item, row[c], null); } } } //call stored procedure to get data. public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); SqlConnection con = new SqlConnection(connectionString); try { cmd = new SqlCommand(SPName, con); cmd.Parameters.AddRange(SqlPrms); cmd.CommandTimeout = 240; cmd.CommandType = CommandType.StoredProcedure; da.SelectCommand = cmd; da.Fill(ds); } catch (Exception ex) { return ex; } return ds; } } 

现在,传递和调用方法的方法如下。

  DataSet ds = DAL.GetRecordWithExtendedTimeOut("ProcedureName"); List model = new List(); if (ds != null) { //Pass datatable from dataset to our DAL Method. model = DAL.CreateListFromTable(ds.Tables[0]); } 

直到日期,对于我的许多应用程序,我发现这是获取数据的最佳结构

哟可能想看看这里的代码。 虽然它不能直接回答您的问题,但您可以调整用于在数据类和业务对象之间进行映射的generics类类型。

此外,通过使用通用,您可以尽快运行转换过程。