3

I have a datatable in which no of columns is dynamic. I need a list with header name and value.I found a question similar to this question.

enter link description here

But can not getting desired output. Output with this solution In Dynamic View :

enter image description here

In Result View enter image description here

I m using this Code for Convert to dynamic object :

    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];
            }
            dynamicDt.Add(dyn);
        }
        return dynamicDt;
    }

Need a output like that :-

enter image description here

How can i achieve this?

Konamiman
  • 49,681
  • 17
  • 108
  • 138
Shailendra Kumar
  • 138
  • 2
  • 12

1 Answers1

0

You can achieve that by modifying the ToDynamic method you are using. The original method is:

public static class DataTableExtensions
{
    public static List<dynamic> ToDynamic(this DataTable dt)
    {
        var dynamicDt = new List<dynamic>();
        foreach (DataRow row in dt.Rows)
        {
            dynamic dyn = new ExpandoObject();
            dynamicDt.Add(dyn);
            //--------- change from here
            foreach (DataColumn column in dt.Columns)
            {
                var dic = (IDictionary<string, object>)dyn;
                dic[column.ColumnName] = row[column];
            }
            //--------- change up to here
        }
        return dynamicDt;
    }
}

Replace the lines between the "change" comments into:

foreach (var columnName in new[] {"A", "B", "C", "D", "E"} )
{
    var dic = (IDictionary<string, object>)dyn;
    if(dt.Columns.Contains(columnName))
        dic[columnName] = row[dt.Columns[columnName]];
    else
        dic[columnName] = 0;
}

That's assuming you need column names A to E, adjust as appropriate if you need more columns.

Konamiman
  • 49,681
  • 17
  • 108
  • 138