amit patel amit patel - 1 year ago 108
ASP.NET (C#) Question

How to convert DataTable to class Object

I have already develop an application which returns DataTable everywhere.

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

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).

For small functionality, I can use Linq no issue.

My question is: how can I change my

to objects of that class?

The sample code is below

string s = DateTime.Now.ToString();
DataTable dt = new DataTable();


for (int i = 0; i < 5000000; i++)
DataRow dr = dt.NewRow();
dr["id"] = i.ToString();
dr["name"] = "name" + i.ToString();


List<Class1> clslist = new List<Class1>();

for (int i = 0; i < dt.Rows.Count; i++)
Class1 cls = new Class1(); = dt.Rows[i]["id"].ToString(); = dt.Rows[i]["name"].ToString();


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

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

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

sll sll
Answer Source

Initialize 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 });

Query itself:

IList<Class1> items = dt.AsEnumerable().Select(row => 
    new Class1
            id = row.Field<string>("id"),
            name = row.Field<string>("name")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download