You can definitely do this with help of 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;
}
Code above will create keys for dictionary from Column names of tables and data for each column will go into corresponding list. It's sort of tuple.
Let's assume your DataTable is a valid dt
var dataObject = TransposeDataTable (dt);
var jsonString = JsonConvert.SerializeObject (dataObject, Formatting.Indented);
After successful conversion, jsonString will contain our good looking Json object. In my case, dt as dummy data so will produce 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"
]
}
sortedand notstored:(