如何将数据表转换为类对象? [英] How to convert DataTable to class Object?

查看:39
本文介绍了如何将数据表转换为类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个应用程序,它在任何地方都返回DataTable.

I have already developed an application which returns DataTable everywhere.

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

Now my client wants to convert (use some part using service stack), so I need to return DTO (objects) in my application.

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

I don't want to change my existing stored procedures or even not want to use LINQ as much as possible (I am not too much aware with LINQ).

对于小功能,我可以使用 Linq 没问题.

For small functionality, I can use Linq no issue.

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

My question is: how can I change my DataTable to objects of that class?

示例代码如下:

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<Class1> clslist = new List<Class1>();

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("<br>");
Response.Write(DateTime.Now.ToString());

我知道,上述方法很耗时,我正在努力寻找替代解决方案.

I know, the above method is time-consuming, and I am trying to find an alternate solution.

是否有任何替代方法(我猜是 LINQ to DataTable)将表的行直接转换为 List?

Is there any alternative way (I guess, LINQ to DataTable) by which it directly converts the rows of tables to List<Class1>?

这样我就可以返回服务堆栈中的对象并继续.

So that I can return objects in my service stack and go ahead.

推荐答案

初始化数据表:

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<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
        {
            id = row.Field<string>("id"),
            name = row.Field<string>("name")
        }).ToList();

这篇关于如何将数据表转换为类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆