DataTable to Dynamic List

format strings

Last day I got a requirement, it need a pivot table. I generated this table in SQL and read it to a datatable. No issues. Then I want convert this datatable to a list. I can’t create a entity because columns are dynamic. I stuck here some time and got a solution .



public static class HelperExtensions
  public static List<dynamic> ToDynamic(this DataTable dt)
    var dynamicDt = new List<dynamic>();
    foreach (DataRow row in dt.Rows)
      dynamic dyn = new ExpandoObject();
      foreach (DataColumn column in dt.Columns)
         var dic = (IDictionary<string, object>)dyn;
         dic[column.ColumnName] = row[column];
    return dynamicDt;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s