這裏全碼:
var dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("CategoryID", typeof(int));
dataTable.Columns.Add("Category", typeof(string));
dataTable.Rows.Add(1, 1, "Category1");
dataTable.Rows.Add(2, 1, "Category2");
dataTable.Rows.Add(3, 2, "Category3");
dataTable.Rows.Add(4, 2, "Category4");
dataTable.Rows.Add(5, 1, "Category5");
dataTable.Rows.Add(6, 3, "Category6");
var dict = dataTable.AsEnumerable()
.GroupBy(row => row.Field<int>("CategoryID"))
.ToDictionary(
g => g.Key.ToString(),
g => g.Select(row => new { Category = row.Field<string>("Category") }).ToList()
);
var jss = new JavaScriptSerializer();
Console.WriteLine(jss.Serialize(dict));
最後一個字符串爲您提供了JSON(我格式化它以提高可讀性):
{
"1":
[
{"Category":"Category1"},
{"Category":"Category2"},
{"Category":"Category5"}
],
"2":
[
{"Category":"Category3"},
{"Category":"Category4"}
],
"3":
[
{"Category":"Category6"}
]
}
的數據表結構不是清楚我的問題,所以我再試一次... ID | CategoryID |類別 ------------------------------------ 1 | 1 | Category1 2 | 1 |類別2 – NShaik
也許嘗試Json.net http://stackoverflow.com/questions/2979922/how-to-convert-datatable-to-json-string-using-json-net – KMoussa