You can definitely do this with lists and dictionaries.
public static IDictionary<string, List<object>> TransposeDataTable(DataTable table) { if (table == null) { return null; } var dicData = new Dictionary<string, List<object>> (); var lstRows = new List<object>[table.Columns.Count]; foreach (DataRow item in table.Rows) { for (var i = 0; i < table.Columns.Count; i++) { if (lstRows [i] == null) { lstRows [i] = new List<object> (); } lstRows [i].Add (item [i]); } } for (var i = 0; i < table.Columns.Count; i++) { dicData.Add (table.Columns [i].ColumnName, lstRows [i]); } return dicData; }
The above code will create the keys for the dictionary from the column names of the tables, and the data for each column will be included in the corresponding list. This is a kind of motorcade.
Suppose your DataTable
is a valid dt
var dataObject = TransposeDataTable (dt); var jsonString = JsonConvert.SerializeObject (dataObject, Formatting.Indented);
After a successful conversion, jsonString
will contain our beautiful Json object. In my case, dt
as dummy data will result in something like.
{ "year": [ "2010", "2011", "2012", "2013", "2014" ], "produceOne": [ "1", "11", "21", "31", "41" ], "ProductTwo": [ "2", "12", "22", "32", "42" ], "ProductThree": [ "3", "13", "23", "33", "43" ] }