如何数据表转换成类对象转换成、数据表、对象

2023-09-03 00:30:23 作者:︶ㄣ殺愛戒愛

我已经开发一种返回DataTable中无处不在的应用程序。 现在,我的客户要转换(使用役堆栈使用某些部分),所以我需要返回的DTO(对象)在我的应用程序。 我不想改变我现有的Storeprocedure甚至不希望使用LINQ尽可能多地。 (我没有太多的了解与LINQ)

I have already develop an application which return DataTable everywhere. Now my client wants to convert (use some part using servie stack), so i need to return DTO (objects) in my application. I don't want to change my existing Storeprocedure or even not want to use LINQ as much as possible. (I am not too much aware with LINQ)

有关小功能,我可以使用LINQ没有任何问题。 我的问题是, 我怎样才能改变我的DataTable对象到该类。 样品code低于

For small functionality, i can use Linq no issue. My question is, How can i change my Datatable to Object of that class. The sample code is below

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, above is time consuming, and so i am trying to find alternative solution.

有没有另一种方式(我猜想,LINQ到数据表),用它直接在表中的行转换成名单,其中,1级&GT;

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

因此​​,我可以在我的服务栈返回对象,并继续前进。

So 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();