I want to convert a C# object or datatable such that, each column becomes a key & values becomes a array
year productOne ProductTwo ProductThree
2010 1 2 3
2011 10 20 30
2012 100 200 300
2013 1000 2000 3000
I am looking to generate following JSON output. Please keep in mind, no of rows and columns are dynamic.
[{
name: productOne ,
data: [1,10,100,1000]
},{
name: productTwo ,
data: [2,20,200,2000]
},{
name: productThree ,
data: [3,30,300,3000]
}]
解决方案DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
DataRow dr = dt.NewRow();
dr[0] = "10";
dr[1] = "20";
dr[2] = "30";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "100";
dr[1] = "200";
dr[2] = "300";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "1000";
dr[1] = "2000";
dr[2] = "3000";
dt.Rows.Add(dr);
List list = new List();
for (int i = 0; i < dt.Columns.Count; i++)
{
dynamic result = new ExpandoObject();
result.name = dt.Columns[i].ColumnName;
result.data = dt.Rows.Cast()
.Select(row => row[i])
.ToArray();
list.Add(result);
}
var op = JsonConvert.SerializeObject(list);